输入流 | 输出流 | |
---|---|---|
字节流 | 字节输入流 InputStream | 字节输出流 OutputStream |
字符流 | 字符输入流 Reader | 字符输出流 Writer |
1. 字节输出流OutputStream
hrows Exception {
//会自动帮忙创建文件,但是文件夹不能建
OutputStream os = new FileOutputStream("E:/AAA/b/f.txt");
String str = "abcd";
//把字符串转换为字节数组
byte[] bytes = str.getBytes();
os.write(bytes);
os.close();//自带flush
}
数据追加续写
public class Demo04OutputStream {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("c.txt", true);
/*追加写10个"你好",并进行换行处理*/
for (int i = 0; i < 10; i++) {
fos.write("\n".getBytes());
fos.write("你好".getBytes());
}
}
}
2.字节输入流InputStream
//字节输入流 (一次一次的读取)
@Test
public void inputstream() throws Exception {
InputStream is = new FileInputStream("E:/AAA/b/f.txt");
byte[] bytes = new byte[3];
int c = is.read(bytes);
c = is.read(bytes);
System.out.println(c);
}
//一次性读取大文件
@Test
public void demoinp() throws Exception{
InputStream is = new FileInputStream("E:/AAA/b/f.txt");
byte[] bytes = new byte[3];
int c= 0;
while ((c=is.read(bytes))!=-1){
String str = new String(bytes);
System.out.println(str);
}
is.close();
}
close方法,当完成流的操作时,必须调用此方法,释放系统资源。