今天需求需要读取文件,写着写着发现自己Java IO的使用体系已经成了一坨粥,乱得很,字节流字符流,缓冲流,打印流杂在了一起,实在惭愧,于是在这儿总结一下,也方便自己遗忘时温习。
字节流
输入字节流 FileInputStream
File file = new File("C:\\Users\\suika\\Desktop\\test.txt");
StringBuffer buffer = new StringBuffer();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
String s = new String(buf, 0, len);
buffer.append(s);
}
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
输出字节流
File file = new File("C:\\\\Users\\\\suika\\\\Desktop\\\\test.txt");
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file, true);
byte[] buf = "这是输出字节流".getBytes();
outputStream.write(buf, 0 , buf.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流
输入字符流
File file = new File("C:\\\\Users\\\\suika\\\\Desktop\\\\test.txt");
FileReader fileReader = null;
try {
StringBuffer buffer = new StringBuffer();
fileReader = new FileReader(file);
char[] buf = new char[1024];
int line = 0;
while ((line = fileReader.read(buf)) != -1) {
buffer.append(new String(buf, 0, line));
}
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
输出字符流
使用的时候奇怪的发现FileWriter没有更新,只有覆盖
File file = new File("C:\\\\Users\\\\gaofeng\\\\Desktop\\\\test.txt");
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
String s = "这是新增的内容";
fileWriter.write(s);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}