文件的读写操作分为字节流和字符流。
字节流的父类是InputStream(读)、OutputStream(写)。它的子类有FileInputStream、FileOutputStream。
字符流的父类是Reader(读)、Writer(写)。它的子类有BufferedReader、BufferedWriter。
字节流的读操作代码:
public static void byteRead(File file) {
try {
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
int n = inputStream.read(bytes);
// 打印new String(bytes, 0, n));
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
字节流的写操作代码:
public static void byteWrite(File file) {
try {
OutputStream outputStream = new FileOutputStream(file);
String text = "Hello World";
byte[] data = text.getBytes();
outputStream.write(data);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
字节流的读出再写入操作代码:
public static void byteReadToWrite(File file,File newFile) {
try {
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
OutputStream outputStream = new FileOutputStream(newFile);
inputStream.read(bytes);
outputStream.write(bytes);
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流的读操作代码:
public static void stringRead(File file) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GB2312"));
String str = reader.readLine();
// 打印str
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流的写操作代码:
public static void stringWrite(File file) {
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"GB2312"));
String text = "Hello World 你好世界";
writer.write(text);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流的读出再写入操作代码:
public static void stringReadToWrite(File file, File newFile) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GB2312"));
String str = reader.readLine();
// 打印str
Writer writer = new FileWriter(newFile);
writer.write(str);
writer.write("stringReadToWrite");
writer.flush();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}