2011年8月30日 星期二

String, Stream互轉

  private static String streamToString(InputStream input) throws Exception {
    String output = "";
    while (input.available() > 0) {
      output += ((char) (input.read()));
    }
    return output;
  }
  private static OutputStream stringToStream(String charset) throws IOException {
    byte[] bytes = charset.getBytes();
    InputStream is = null;
    OutputStream os = null;
    is = new ByteArrayInputStream(charset.getBytes("UTF-8"));
    int numRead;
    while ((numRead = is.read(bytes)) >= 0) {
      os.write(bytes, 0, numRead);
    }
    return os;
  }

SQL*Loader基本用法

指令:
sqlldr username/password control=loader.ctl DIRECT=TRUE

loader.ctl:

load data
infile 'd:\work\mydata.csv'
append into table SPECIAL_PRODUCT
fields terminated by "," optionally enclosed by '"'         
( UUID, PROD_NO, PROD_NAME, PRICE )

mydata.csv:

"10013","Scott Tiger","1000",40
"10014","Frank Naude","500",20

參考:
http://www.orafaq.com/wiki/SQL*Loader_FAQ

EnterpriseDB對應的工具是EDB*Loader:
http://www.enterprisedb.com/docs/en/8.4/oracompat/Postgres_Plus_Advanced_Server_Oracle_Compatibility_Guide-191.htm

用jsch執行遠端ssh command的範例

jsch home: http://www.jcraft.com/jsch/

package test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JschTest {
  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
    JSch jsch = new JSch();
    System.out.println("Getting session...");
    String host = "yourhost";
    String userName = "userName";
    String password = "password";
    String cmd = "ls";
    Session session = jsch.getSession(userName, host, 22);
    System.out.println("session " + session.getUserName() + "@" + session.getHost() + " established");
    session.setPassword(password);
    Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(40000);
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(cmd);
    channel.connect();
    channel.run();
    // get I/O streams for remote scp
    OutputStream out = channel.getOutputStream();
    InputStream in = channel.getInputStream();
    String output = "";
    while (channel.isClosed() != true) {
      output += streamToString(in);
    }
    System.out.println("output:\n" + output);
    channel.disconnect();
    session.disconnect();
  }
  private static String streamToString(InputStream input) throws Exception {
    String output = "";
    while (input.available() > 0) {
      output += ((char) (input.read()));
    }
    return output;
  }
}