输入输出概述
输入输出要点
-
java通过流(Stream)统一了所有的输入输出操作
-
流是对输入输出的抽象
-
以应用程序为核心:
应用程序从流读取数据(流—>应用程序)叫做输入(Input)
从应用程序向流传数据(应用程序—>流)叫做输出 (Output) -
所有的流操作都需要处理异常
-
流中的数据本质都是字节序列
流的分类
- 字节流
所有字节流的父类:抽象流 InputStream和OutputStream - 字符流
所有字符流的父类:抽象流 Reader和Writer
文件字节输入输出流
文件字节输入流
FileInputStream
1. 构造方法
FileInputStream(String name)
FileInputStream(File file)
2. int read(byte [])方法
返回值 int 参数 byte[]
public class FileInputStreamTest {
public void readFile() {
try {
FileInputStream inputStream = new FileInputStream("d://try.txt");
byte b[] = new byte[32];
int n = 0;
while ((n = inputStream.read(b)) != -1) {
System.out.print(new String(b, 0, n, "UTF-8"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FileInputStreamTest fileInputStreamTest = new FileInputStreamTest();
fileInputStreamTest.readFile();
}
}
文件字节输出流
FileOutputStream
1. 构造方法
FileOutputStream(String name)
FileOutputStream(File file)
2. void write(byte [])方法
无返回值 参数 byte[]
文件字符输入输出流
FileReader和FileWriter
直接对全字符文件的读写机制
注:指定以ANSI格式读取,若文件为UTF-8格式可以考虑InputStreamReader
public class FileReaderTest {
public void go() throws IOException {
FileReader fileReader=new FileReader("d://try.txt");
char b[]=new char[32];
int n=0;
while((n=fileReader.read(b))!=-1) {
System.out.println(new String(b,0,n));
}
}
public static void main(String[] args) {
FileReaderTest fileReaderTest=new FileReaderTest();
try {
fileReaderTest.go();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
InputStreamReader和OutputStreamWriter
将FileInputStream和FileOutputStream二次包装成指定编码格式的字符流
public class InputStreamReaderTest{
public void go() throws IOException {
FileInputStream inputStream=new FileInputStream("d://try.txt");
InputStreamReader inputStreamReade=new InputStreamReader(inputStream,"UTF-8");
char[]b=new char[32];
int n=0;
while((n=inputStreamReade.read(b))!=-1) {
System.out.println(new String(b,0,n));
}
}
public static void main(String[] args) {
InputStreamReaderTest inputStreamReaderTest=new InputStreamReaderTest();
try {
inputStreamReaderTest.go();
}catch(IOException e) {
e.printStackTrace();
}
}
}
缓冲流
- BufferedReader和BufferedWriter是在字符流基础上更高效,实用的字符流访问方法
- BufferedReader和BufferedWriter InputStreamReader和OutputStreamWriter在内,大部分流并不只是只针对文件流进行读写
BufferedReader最常用的方法 String readLine(); BufferedWriter最常用的方法void newLine();该方法所有平台都适用
class InputStreamReaderTest{
public void go() throws IOException {
FileInputStream inputStream=new FileInputStream("d://try.txt");
InputStreamReader inputStreamReade=new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader=new BufferedReader(inputStreamReade);
//进行了三次包装
String n=null;
while((n=bufferedReader.readLine())!=null) {
System.out.println(n);
}
}
public static void main(String[] args) {
InputStreamReaderTest inputStreamReaderTest=new InputStreamReaderTest();
try {
inputStreamReaderTest.go();
}catch(IOException e) {
e.printStackTrace();
}
}
}