文件的读写操作(Java版)
2021-02-24 本文已影响0人
方_f666
IO的类型
传输方向:输入流、输出流。
传输内容:字节流、字符流:字节流可以传输任何文件,字符流只能传输文本文件。
功能上:节点流、过滤流。节点流有基本的读写功能,过滤流在节点流的基础上增加功能。
字节流的父类是InputStream(读)、OutputStream(写),
节点流:FileInputStream、FileOutputStream,
过滤流:DataInputStream、DataOutputStream。
字符流父类是Reader、Writer,
节点流:FileReader、FileWriter,
过滤流:BufferedReader、BufferedWriter,
桥转换流:InputStreamReader、OutputStreamWriter,
字符流的编码方式和解码方式需要相同。
字节流的读操作代码:
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();
}
}