字符流读写文本文件(txt,csv等)
private void writeBufferedWriter() throws IOException {
String path = "/data/output.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
bw.write("我是一个文本文件。");
}
}
private void readBufferedReader() throws IOException {
String path = "/data/output.txt";
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
}
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
while ((line = br.readLine()) != null) {
System.out.print(line);
}
}
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
char[] buf = new char[1024];
int length;
while ((length = br.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
}
字节流读写音视频、二进制文件等,文本文件也可以但不推荐
private void writeBufferedOutputStream() throws IOException {
String path = "/data/output.txt";
String content = "文件内容";
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) {
byte[] bytes = content.getBytes();
bos.write(bytes);
}
}
private void readBufferedInputStream() throws IOException {
String path = "/data/input.txt";
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))) {
byte[] buf = new byte[1024];
int length;
while ((length = bis.read(buf)) != -1) {
String str = new String(buf, 0, length);
System.out.print(str);
}
}
}