1 package test.inoutstream;
2
3
4 import org.junit.Test;
5
6 import java.io.*;
7
8 public class TestStream {
9 @Test
10 public void TestFile(){
11 File file = new File("word.txt");
12 if (!file.exists()){
13 try{
14 file.createNewFile();
15 //创建FileOutputStream对象:
16 FileOutputStream outputStream = new FileOutputStream(file);
17 //创建byte型数组
18 byte buy[] = "鸡毛换糖了".getBytes();
19 outputStream.write(buy);//将数组中的信息写入到文件中
20 outputStream.close();
21 }catch (Exception e){
22 e.printStackTrace();
23 }
24 try {
25 //创建FileInputStream类对象
26 FileInputStream inputStream = new FileInputStream(file);
27 byte byt[] = new byte[1024];//创建byte数组
28 int len = inputStream.read(byt);
29 System.out.println("文件中的信息是:"+ new java.lang.String(byt,0,len));
30 inputStream.close();
31 }catch (Exception e){
32 e.printStackTrace();
33 }
34
35 }
36
37 }
38
39 /**
40 * FileInputStream和FileOutStream的不足:
41 * 只提供对字节或者字节数组的读取(比如汉字要转换)
42 * 可能会出现乱码
43 *
44 * 引入FileWriter和FileReader
45 * FileReader:从内存中读文件
46 * FileWriter:往内存中写文件
47 */
48
49 /**
50 * 带缓存的输入和输出流
51 * BufferedInputStream与BufferedOutStream
52 *开辟缓存区,多了几个方法:skip() mark()和reset
53 * BufferedReader和BufferedeWriter类
54 */
55
56 /**
57 * 数据输入/输出流
58 * 运行应用程序以与机器无关的方式从底层输入流中读取基本的java数据类型,在读写时,无需关注哪个字节
59 */
60
61 @Test
62 public void TestDataIOStream(){
63 try{
64 //创建流对象
65 FileOutputStream fs = new FileOutputStream("word.txt");
66 //创建DataOutputStream对象,相当于给这个流套了个套子,这样就可以实现多个功能了
67 DataOutputStream ds = new DataOutputStream(fs);
68 ds.writeUTF("使用WriteUTF方法写入数据");
69 ds.writeBytes("使用writeBytes写入数据");
70 ds.close();
71 //创建FileInputStream对象
72 FileInputStream fls = new FileInputStream("word.txt");
73 DataInputStream dis = new DataInputStream(fls);
74 System.out.println(dis.readUTF());
75 }catch (Exception e){
76 e.printStackTrace();
77 }
78 }
79 }