2015年5月24日:
IO流有两大类:
1:字符流
2:字节流
3:转换流
先来说第一个字符流
1):字符流通常是用来操作纯文本数据的,一般对于文本数据我们使用字符流FileWriter和FileReader
比如:
需求:把一个文本文件的内容输出到控制台上:
import java.io.*;
public class IODemo
{
public static void main(String[] args) throws Exception
{
method1();
}
public static void method1() throws Exception
{
BufferedReader bfw = new BufferedReader(new FileReader("IODemo.java"));
String line = null;
while((line = bfw.readLine()) != null)
{
System.out.println(line);
}
bfw.close();
}
}
为了提高效率我们可以选择缓冲区技术BfferedReader();
如果不选择缓冲区技术的话 还可以这样来做:
import java.io.*;
public class IODemo
{
public static void main(String[] args) throws Exception
{
method2();
}
public static void method2() throws Exception
{
FileReader fr = new FileReader("IODemo.java");
char[] buf = new char[10];
int len;
while ((len = fr.read(buf)) != -1)
{
System.out.print(buf);
}
fr.close();
}
}
记住在打印的时候是System.out.print(); 后面没有换行符 因为没有把换行符读入, 所以一旦字符数超过规定的长度,那么就会混乱。
那么再看一个需求:
从硬盘上拷贝一个文本文件:
那么我们可以使用缓冲区技术会更加高效:
public static void method3() throws Exception
{
BufferedReader bfw = new BufferedReader(new FileReader("IODemo.java"));
BufferedWriter bfr = new BufferedWriter(new FileWriter("Copy.java"));
String line = null;
while ((line = bfw.readLine()) != null)
{
bfr.write(line);
bfr.newLine();
}
bfr.close();
bfw.close();
}
记住:必须在写入的后面加一句bfr.newLine(); 这是把换行符写入,因为在读入的时候并没有把换行符读入。
再来看字节流:
InputStream OutputStream
可以这样来做:
public static void method4() throws Exception
{
FileInputStream fis = new FileInputStream("IODemo.java");
FileOutputStream fos = new FileOutputStream("Copy_1.java");
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1)
{
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
len返回的是读取的字节数大小所以在写入另一个文件的时候可以这样:fos.write(buf, 0, len): 其中len表示写入的长度
当然我们也可以偷点懒 可以这样做:
public static void method5() throws Exception
{
FileInputStream fis = new FileInputStream("IODemo.java");
FileOutputStream fos = new FileOutputStream("Copy_2.java");
byte[] buf = new byte[fis.available()];
fos.write(buf);
fis.close();
fos.close();
}
这样就可以不用进行循环了 但是这样有风险 如果当文件很大,而电脑的内存小于文件的大小的时候就不可以使用这种方法了!!!切记
需求:复制图片
那么必须使用字节流了
public static void method6() throws Exception
{
FileInputStream fis = new FileInputStream("1.jpg");
FileOutputStream fos = new FileOutputStream("2.jpg");
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1)
{
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
那么接下来再看转换流:
转换流就是字节流转换成字符流:
InputStreamReader OutputStreamWriter
需求:
从键盘上输入数据 并且写入一个文件
那么就要使用转换流了:
public static void method7() throws Exception
{
BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Out.txt")));//使用转换流
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = bfr.readLine()) != null)
{
if (line.equals("886")) break;
bfw.write(line);
bfw.newLine();
}
bfr.close();
bfw.close();
}