java/ファイル入出力
Last-modified: 2018-11-14 (水) 15:24:10 (2919d)
java それぞれ、次のimportが必要です。
import java.io.*;
テキストファイル読み込み †
FileReader fr;
try {
fr = new FileReader("ファイル名");
int c;
String str = new String();
while ((c = fr.read()) != -1) {
str = str + (char)c;
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (fr != null) {
fr.close();
fr = null;
}
} catch (IOException e2) {
}
}
テキストファイル書き込み †
FileWriter fw;
try {
fw = new FileWriter("ファイル名");
fw.write("書き込みたい文字列");
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException e2) {
}
}
バッファ付きテキストファイル読み込み †
BufferedReader br;
try {
br = new BufferedReader(new FileReader("ファイル名"));
String str = new String();
while ((str = br.readLine()) != null) {
System.out.println(str); // 処理を記述
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (br != null) {
br.close();
br = null;
}
} catch (IOException e2) {
}
}
バッファ付きテキストファイル書き込み †
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter("ファイル名"));
bw.write(書き込みたいデータ);
bw.newLine; // 行区切り
bw.flush();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (bw != null) {
bw.close();
bw = null;
}
} catch (IOException e2) {
}
}
バイナリファイル byte単位の読み込み †
FileInputStream fis;
try {
fis = new FileInputStream("ファイル名");
int b;
while ((b = fis.read()) != -1) {
System.out.println(b); // 処理を記述
}
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (IOException e2) {
}
}
バイナリファイル byte単位の書き込み †
FileOutputStream fos;
try {
fos = new FileOutputStream("ファイル名");
fos.write(書き込みたいデータ);
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (fos != null) {
fos.close();
fos = null;
}
} catch (IOException e2) {
}
}
バイナリファイル各種データ読み込み †
DataInputStream dis;
try {
dis = new DataInputStream(new BufferedInputStream(new FileInputStream("ファイル名")));
// dis = new DataInputStream(new FileInputStream("ファイル名")); バッファ無しの場合
int i = dis.readInt();
String str = dis.readUTF();
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (dis != null) {
dis.close();
dis = null;
}
} catch (IOException e2) {
}
}
バイナリファイル各種データ書き込み †
DataOutputStream dos;
try {
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("ファイル名")));
// dos = new DataOutputStream(new FileOutputStream("ファイル名")); バッファ無しの場合
dos.writeInt(書き込みたいint型データ);
dos.writeUTF(書き込みたい文字列データ);
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (dos != null) {
dos.close();
dos = null;
}
} catch (IOException e2) {
}
}