1 package bao5;
2 import java.io.*;
3 public class Text3
4 {
5
6 public static void main(String[] args)
7 {
8 try
9 {
10 //文件输出流
11 File file=new File("d:/test.txt");
12 if(!file.exists())
13 {
14 file.createNewFile();
15 System.out.println("创建文件成功");
16 }
17 //构造字节输出流,指定目标文件
18 FileOutputStream fos=new FileOutputStream(file,true);
19 //数据源
20 String str="这是文件的写入内容\n";
21 //把数据源,转成byte[]
22 byte[] b=str.getBytes();
23 //写入数据
24 fos.write(b);
25 //关闭流,释放文件
26 fos.close();
27 System.out.println("写入文件完成");
28
29
30
31 //字节输入流
32 FileInputStream fis=new FileInputStream(file);
33 //装在读入的数据
34 byte[] d=new byte[1024];
35 //全部内容
36 String str2="";
37 //返回值int类型代表读入数据的长度
38 int i=fis.read(d);
39 while(i>0)
40 {
41 //从byte型转成需要的数据类型
42 String str1=new String(d,0,i);//从0开始到i结束
43 str2=str2+str1;
44 //继续读
45 i=fis.read(d);
46 }
47 System.out.println("读入的内容是="+str2);
48
49 fis.close();
50
51 }
52
53
54 catch (Exception e)
55 {
56 e.printStackTrace();
57 }
58
59 }
60
61 }