-
常用的字节输入流有:InputStream ,FileInputStream,BufferedInputStream
- 常用的字节输出流有:OutputStream,FileOutputStream,BufferedOutputStream
- 常见的字符输入流有:Reader,InputStreamReader,FileReader,BufferedReader
- 常见的字符输出流有:Writer,OutputStreamWriter,FileWriter,BufferedWriter
- Buffered修饰的流是缓存的流,信息从内存中操作,效率比一般流操作效率高
demo如下:
public class Iotest {
public static void main(String[] args) {
File file = new File("E:\\iotest\\wl.txt");
/*
* 字节流 向文件中保存内容
*/
try (OutputStream os = new FileOutputStream(file, true)) {
String str = "\r\n hello world";
byte[] ss = str.getBytes("UTF-8");
os.write(ss);
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字节流 BufferedInputStream 向文件中保存信息
*/
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true))) {
String str2 = "\r\n buffered hello world";
byte[] bytes = str2.getBytes("UTF-8");
bos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字节流 从文件中读取文件信息
* */
try (InputStream inputStream = new FileInputStream(file)) {
byte[] input = new byte[1024];
int len = 0;
while ((len = inputStream.read(input)) != -1) {
System.out.println(new String(input, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字节流 BufferInputStream 从文件中读取内容
* */
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
int len = 0;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字符流 向文件中保存信息
* */
try (Writer writer = new FileWriter(file, true)) {
String str2 = "\r\n 你好 中国!";
writer.write(str2);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字符流 BufferWriter 向文件中保存内容
* */
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
bw.write("\r\n Buffered 你好 中国!");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字符流 读取文件中信息
* */
try (Reader reader = new FileReader(file)) {
char[] r = new char[1024];
int len = 0;
while ((len = reader.read(r)) != -1) {
System.out.println(new String(r, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
/*
* 字符流 BufferReader 从文件中读取信息
* */
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}