有关于流的概念:
程序中的所有数都是以流的方式进行传输或或保存的,保存的内容嗾使字节文件,程序需要数据的时候 要使用输入流读取数据,程序需要将一些数据保存的时候没救要用输出流来实现。
字节流的输出依赖OutputStream、输入依赖InputStream
字符流的输出主要使用Writer类、输入流依赖Reader类
1、字节流在硬盘上创建文件,并写入内容:
1 import java.io.File;
2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.OutputStream;
5
6 public class Test11 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
10 String str=”Hello World”;
11 byte[] b=str.getBytes();
12 out.write(b);//因为是字节流,所以要转化成字节数组进行输出
13 out.close();
14 }
15 }
2、字节输入流读取文件内容
1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 public class Test12 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 InputStream in=new FileInputStream(f);
10 byte[] b=new byte[1024];
11 int len=in.read(b);
12 in.close();
13 System.out.println(new String(b,0,len));
14 }
15 }
3、字符流在硬盘上创建文件,并写入内容:
1 import java.io.File;
2 import java.io.FileWriter;
3 import java.io.IOException;
4 import java.io.Writer;
5
6 public class Test16 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 Writer out=new FileWriter(f);
10 String str=”Hello World”;
11 out.write(str);
12 out.close();
13 }
14 }
4、字节输入流读取文件内容
1 import java.io.File;
2 import java.io.FileReader;
3 import java.io.IOException;
4 import java.io.Reader;
5
6 public class Test18 {
7 public static void main(String[] args) throws IOException {
8 File f = new File(“d:” + File.separator+”test.txt”);
9 Reader input=new FileReader(f);
10 char[] c=new char[1024];
11 int len=input.read(c);
12 input.close();
13 System.out.println(new String(c,0,len));
14 }
15 }