一、Java I/O概述
分两类:字符流和字节流。然后就是输入和输出。
FileReader FileWriter BufferedReader BufferedWriter (File-Buffered-Object)InputStream OutputStream
字节流:图片、视频文件中存储的都是二进制的字节(byte)。
不管是文本、还是图书、视频最终在磁盘上的时候都是按照byte存储的。
文件(输入流)内存(输出流)文件
二、I/O的使用的文件读写
字符流
public static void copyByChar()
{
FileReader fileReader = null;
FileWriter fileWriter = null;
try
{
fileReader = new FileReader(DATA_FILE_NAME);
fileWriter = new FileWriter(OUTPUT_FILE_NAME);
int value;
while((value = fileReader.read()) != -1)
{
System.out.println(value);
fileWriter.write(value);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fileReader.close();
fileWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//
FileReader fileReaderByStream = new FileReader("d:\\test.txt");
FileReader fileReaderByFile = new FileReader(new File("d:\\test.txt"));
直接传入字符串的时候,Java内部其实会new一个File对象的
字节流
public static void copyByByte()
{
FileInputStream inStream = null;
FileOutputStream outStream = null;
try
{
inStream = new FileInputStream(DATA_FILE_NAME);
outStream = new FileOutputStream(OUTPUT_FILE_NAME);
int value;
while((value = inStream.read()) != -1)
{
System.out.print(value);
outStream.write(value);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
inStream.close();
outStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
带缓冲的读写:一次读写一批数据
public static void copyWithBuffer()
{
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try
{
bufferedReader = new BufferedReader(new FileReader(DATA_FILE_NAME));
bufferedWriter = new BufferedWriter(new FileWriter(OUTPUT_FILE_NAME));
int value;
while((value = bufferedReader.read()) != -1)
{
System.out.println(value);
bufferedWriter.write(value);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bufferedReader.close();
bufferedWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
流的关闭:谁使用谁关闭
//行读行写
while ((temp = bufferedReader readLine()) != null ){
bufferedWriter.write(temp+"\n");
System.out.println(temp);
}