字节字符输入输出流
** 以下内容均可以直接运行 **
字符字节输入输出流其实为4个流
- 字节输入流
- 字节输出流
- 字符输入流
- 字符输出流
简介
输入输出流是最基本的I/O流,后续的缓冲流打印流都是基于输入输出流去包装的
字节流是以字节为单位流,与其对应的是字符流Writer和Reader
问题
- 流是什么?流是抽象概念,可以理解为建立了一个流就是建立了一个文件与程序的通信管道,我们通过流对文件进行输入输出操作
- 为什么要有字符字节流之分? 最直观的区别就是字节流可以通向任何文件,而字符流只可以通向文本文件。使用字符流可以增加对文件的使用效率
注意事项
- 输入输出流一定要记得使用 .close() 方法关闭,这里没有使用的原因是在java1.7中加入了 try(){} 的新功能,在括号中放入的语句会自动关闭流,如 try(OutputStream out = new FileOutputStream(f))
- 会自动创建路径下的文件,但是不会创建路径
OutputStream和InputStream
import java.io.*;
public class ByteStream {
public static void main(String[] args) {
byteOut();
byteIn();
}
private static void byteOut(){
File f = new File("c://test//byteOut.txt");
try(OutputStream out = new FileOutputStream(f)){
System.out.println("字节流输出中...");
String s = "test 1 success";
out.write(s.getBytes());
System.out.println("字节流输出成功,字节流关闭");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
private static void byteIn(){
File f = new File("c://test//byteOut.txt");
try(InputStream in = new FileInputStream(f)){
System.out.println("字节流输入中...");
byte[] b = new byte[1024];
int lens = -1;
while((lens = in.read(b))!=-1) {
System.out.println(new String(b,0,lens));
}
System.out.println("字节流输出成功,字节流关闭");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Reader和Write
import java.io.*;
public class StringStream {
public static void main(String[] args) {
stringOut();
streamIn();
}
private static void stringOut(){
File f = new File("c://test//stringOut.txt");
try(Writer wri = new FileWriter(f)){
System.out.println("字符流输出中...");
String s = "test 2 success";
wri.write(s);
System.out.println("字符流输出成功,字符流关闭");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
private static void streamIn(){
File f = new File("c://test//stringOut.txt");
try(Reader re = new FileReader(f)){
System.out.println("字符流输入中...");
char[] ch = new char[1024];
int lens = -1;
while((lens = re.read(ch))!=-1) {
System.out.println(new String(ch,0,lens));
}
System.out.println("字符流输出成功,字节流关闭");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}