Java四种读写文件操作

第一种:字节流读取文本文件

1.字节输入流InputStream

//创建一个文件输入流对象 
        //作用:打通硬盘和内存的通道    创建了一个和硬盘上文件绑定的文件流  
        FileInputStream fis=new FileInputStream("D:\\123.txt");
        //创建缓存区大小是1k  承载1k数据的一个缓冲区    大家:就是内存中的一块区域  。
        //主要是在内存和硬盘之间做数据交换的临时存储区
        byte[]bytes=new byte[1024];
        int date=0;
        StringBuffer sb=new StringBuffer();
        //文件没有读取完毕,下次需要继续读取
        while((date=fis.read(bytes))!=-1){
            //没读取一次,将读取到的字节内容,转成字符串
            String temp=new String(bytes,0,date);
            //读取到缓存区中的有效字节数,转成字符串
            sb.append(temp);
            System.out.println("======有效字节======:"+date);
        
        
        }
        System.out.println(sb.toString());
        fis.close();//关闭流

2.字节输出流OutputStream

1 //构建一个文件输出流对象
2   FileOutputStream fos=new FileOutputStream("D:\\123.txt");
3   //利用文件输出流的方法把数据写入文本文件中
4   String temp="123456789";
5   byte[]bytes=temp.getBytes();
6   fos.write(bytes);//利用write方法将数据写入文件中 
7   fos.close();//关闭流
8   System.out.println("写入成功!");

第二种:字符流 char  FileReader FileWriter

在不同的操作系统和不同的编码方式下  char和比byte之间的关系不是固定的

一般认为:gbk/gb2312 ,2个byte

      utf-8  3个byte

1 FileWriter fw=new FileWriter("D:\\123.txt");
2         fw.write("啦啦啦啦啦啦啦啦啦");
3         fw.close();
4         System.out.println("写入成功!");
5         

第三种 :带缓冲区的字符读取和写入方案

BufferedReader  BufferedWriter缓存区 存储的数据默认是1024byte

 1 public static void main(String[] args) throws Exception {
 2         //读取
 3         FileReader fr=new FileReader("D:\\123.txt");
 4         BufferedReader br=new BufferedReader(fr);
 5         String line=br.readLine();//读取一行数据
 6         while(line!=null){
 7             System.out.println(line);
 8             line=br.readLine();
 9         }
10         br.close();
11         fr.close();
12         
13         
14         //写入
15         FileWriter fw=new FileWriter("D:\\123.txt");
16         BufferedWriter bw=new BufferedWriter(fw);
17         bw.write("\r\n噜噜噜噜噜");
18         bw.newLine();
19         bw.write("乐乐乐乐乐乐乐乐");
20         bw.close();
21         fw.close();
22         System.out.println("写入成功!");
23     }
24 
25 }

第四种:二进制方式的读取和写入方案 DataInputStream DataOutputStream

 1 public static void main(String[] args) throws Exception {
 2         InputStream is=new FileInputStream("D:\\123.jfif");
 3         DataInputStream dis=new DataInputStream(is);
 4         
 5         OutputStream os=new FileOutputStream("F:\\456.jfif");
 6         DataOutputStream oos=new DataOutputStream(os);
 7         byte[]bytes=new byte[1024];
 8         int data=0;
 9         while((data=dis.read(bytes))!=-1){
10             oos.write(bytes,0,data);
11         }
12         oos.close();
13         dis.close();
14         os.close();
15         is.close();
16         System.out.println("212122122");
17 
18     }
 

猜你喜欢

转载自www.cnblogs.com/aaaaliling/p/9067021.html