Java
2012年03月29日
【Java】CSVファイルを文字コード指定でコピー
/**
* csvファイルの作成+文字コード指定
* @param path コピー先ファイルを入れるディレクトリのパス
* @param outputName コピー元ファイルの名前
* @param inputName コピー先ファイルの名前
* @throws IOException
*/
static void copyCSV(String path,String outputName,String inputName) throws IOException{
File from = new File("./data/" + inputName + ".csv"); // コピー元File
File to = new File(path+"/" + outputName + ".csv"); // コピー先File
//文字コード指定で書き出す
InputStreamReader br;
String line;
// 文字コード指定で読み込む
br = new InputStreamReader (new FileInputStream(from),"SJIS");
LineNumberReader lnr = new LineNumberReader(br);
// 文字コード指定で書き込む
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to),"SJIS")));
// 最終行まで、一行ずつ読み込み→書き込み
while ((line = lnr.readLine()) != null) {
pw.println(line);
}
br.close();
lnr.close();
pw.close();
}
【Java】指定行の入れ替え
/**
* 指定行の入れ替え+Fileコピー
* @param in 読み込んだファイルの行
* @param out ファイル書き出し
* @param lineNumber 書き換える行番号
* @param s 書き換える文字列
*/
private static void replace(LineNumberReader in, PrintWriter out, int lineNumber,String s) throws IOException {
String line;
// 最終行まで繰り返す
while ((line = in.readLine()) != null) {
// 入れ替え行か判定
if (in.getLineNumber() == lineNumber) {
out.println(s); // 入れ替え行だったら、文字列を入力
} else {
out.println(line); // 入れ替え行でなければ、コピー
}
}
}
2012年01月26日
【Java】バイナリファイルをコピーする
【準備】
《バイナリファイルをコピーする》
import java.io.*;
《バイナリファイルをコピーする》
/**
* バイナリファイルをコピー&ファイル名書き換え
* @param inPath コピー元ファイルのパス
* @param inputName コピー元ファイルの名前
* @param outPath コピー先ファイルのパス
* @param outputName コピー先ファイルの名前
* @throws IOException
*/
static void createFig(String inPath ,String inputName , String outPath , String outputName ) throws IOException {
File inputFig = new File(inPath +"//" + outputName + ".pdf");
BufferedInputStream input = new BufferedInputStream(new FileInputStream(inputFig));
File outputFig = new File(outPath + "//" + outputName + ".pdf");
BufferedOutputStream output= new BufferedOutputStream(new FileOutputStream(outputFig));
int bf;
while ((bf = input.read()) >= 0){
output.write(bf);
}
output.flush();
output.close();
input.close();
}
【Java】ファイルに文字コード指定で書き出す
例えば、
csvファイルを作成し、作成したファイルに以下を書き出す場合、
・文字コード:SJIS
・入力文字:aaa
↓のようなプログラムになる。
《newFile.csvの中身(SJISで開く)》
csvファイルを作成し、作成したファイルに以下を書き出す場合、
・文字コード:SJIS
・入力文字:aaa
↓のようなプログラムになる。
File createFile = new File("./newFile.csv");
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(createFile),"SJIS")));
pw.println("aaa");
pw.close();
《newFile.csvの中身(SJISで開く)》
aaa