zoukankan      html  css  js  c++  java
  • 文件写入与读取

    1.流的基类

    字节流的两个基类InputStream和OutputStream:以字节为单位,是所有字节输入和输出流的父类;

    字符流的两个基类Reader和Writer:以字符(两个字节)为单位。

    凡是以InputStreamOutputStream结尾的类型为字节流,凡是以ReaderWriter结尾的均为字符流。

     import java.io.*;
     
     public class FileInputStreamTest {//字节流读取文件
     
         public static void main(String[] args) throws IOException {
             //创建字节输入流
    File file=new File("文件路径");
    FileInputStream fis = new FileInputStream(file); //定义结束标志,可用字节数组读取
            int i =0 ;
            while((i = fis.read())!=-1){
                //i 就是从文件中读取的字节,读完后返回-1
            }
            //关闭流
            fis.close();
            //处理异常
    } }
       import java.io.*;

    public class FileOutputStreamTest {//字节流写入文件

         public static void main(String[] args) throws IOException {
             //指定要写到的文件目录及名称
            File file =new File("文件路径");
            //创建文件读入流对象
            FileOutputStream fos =new FileOutputStream(file);
            //定义结束标志
            fos.write(要写出的字节或者字节数组);
            //刷新和关闭流
            fos.flush();
            fos.close();
            //处理异常

        }
    }
     1 import java.io.*;
     2 
     3 public class FileReaderTest{//字符流读取文件
     4     public static void main(String[] args) throws IOException{
     5         FileReader fr = null;
     6         try{
     7             //创建字符输入流
     8             fr = new FileReader("FileReaderTest.java");
     9             //创建一个长度为32的“竹筒”
    10             char[] cbuf = new char[32];
    11             //用于保存实际读取的字符数
    12             int hasRead = 0;
    13             //使用循环来重复“取水”过程
    14             while ((hasRead = fr.read(cbuf)) > 0 ){
    15                 //取出“竹筒”中水滴(字节),将字符数组转换成字符串输入!
    16                 System.out.print(new String(cbuf , 0 , hasRead));
    17             }
    18         }
    19         catch (IOException ioe){
    20             ioe.printStackTrace();
    21         }
    22         finally{
    23             //使用finally块来关闭文件输入流
    24             if (fr != null){
    25                 fr.close();
    26             }
    27         }
    28     }
    29 }
    import java.io.*;
    public class FileOutputStreamTest {//通过字节流实现文件复制(读取写入)
        public static void main(String[] args) throws IOException {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                //创建字节输入流
                fis = new FileInputStream("FileOutputStreamTest.java");
                //创建字节输入流
                fos = new FileOutputStream("newFile.txt");
                byte[] bbuf = new byte[32];
                int hasRead = 0;
                //循环从输入流中取出数据
                while ((hasRead = fis.read(bbuf)) > 0) {
                    //每读取一次,即写入文件输出流,读了多少,就写多少。
                    fos.write(bbuf, 0, hasRead);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                //使用finally块来关闭文件输入流
                if (fis != null) {
                    fis.close();
                }
                //使用finally块来关闭文件输出流
                if (fos != null) {
                    fos.close();
                }
            }
        }
    }
     1 import java.io.*;
     2 
     3 public class FileWriterTest {//向文件中输入字符
     4 
     5     public static void main(String[] args) throws IOException {
     6         FileWriter fw = null;
     7         try {
     8             //创建字符输出流
     9             fw = new FileWriter("poem.txt");
    10             fw.write("锦瑟 - 李商隐
    ");
    11             fw.write("锦瑟无端五十弦,一弦一柱思华年。
    ");
    12             fw.write("庄生晓梦迷蝴蝶,望帝春心托杜鹃。
    ");
    13             fw.write("沧海月明珠有泪,蓝田日暖玉生烟。
    ");
    14             fw.write("此情可待成追忆,只是当时已惘然。
    ");
    15         } catch (IOException ioe) {
    16             ioe.printStackTrace();
    17         } finally {
    18             //使用finally块来关闭文件输出流
    19             if (fw != null) {
    20                 fw.close();
    21             }
    22         }
    23     }
    24 }

    2.缓冲技术:

    Java使用了文件缓冲技术,其优点有:
        提高了I/O的性能
        在内存中开辟一块区域,称为缓冲区
        当缓冲区满时一次写入到磁盘中。

    缓冲流是对流的操作的功能的加强,提高了数据的读写效率。既然缓冲流是对流的功能和读写效率的加强和提高,所以在创建缓冲流的对象时应该要传入要加强的流对象。
    相关的Java类:
        BufferedInputStream/BufferedOutputStream:适合于包容二进制数据的文件
        BufferReader/BufferWriter:适合于读写文本文件。

    //从文件中读入字串

            //指定要写到的文件目录及名称
            File file =new File("文件路径");
            //2.创建文件读入流对象
            FileOutputStream fos =new FileOutputStream(file);
            //3.创建缓冲流对象加强fos功能

           BufferedOutputStream bos=new BufferedOutputStream(fos);

    合并:BufferedInputStream bis =new BufferedInputStream(new FileInputStream(new File("文件路径")));

    缓冲技术示例:

     1 import java.io.*;
     2  
     3 public class BufferedStreamDemo {//利用缓冲字节流复制文件
     4     public static void main(String[] args) {
     5         try {
     6             byte[] data = new byte[1]; 
     7 
     8             File srcFile = new File("BufferedStreamDemo.java"); 
     9             File desFile = new File("BufferedStreamDemo.java.bak"); 
    10 
    11             BufferedInputStream bufferedInputStream = 
    12                 new BufferedInputStream(
    13                          new FileInputStream(srcFile)); 
    14             BufferedOutputStream bufferedOutputStream = 
    15                 new BufferedOutputStream(
    16                          new FileOutputStream(desFile));
    17  
    18             System.out.println("复制文件:" + 
    19                              srcFile.length() + "字节");
    20 
    21             while(bufferedInputStream.read(data) != -1) { 
    22                 bufferedOutputStream.write(data); 
    23             }
    24             
    25             // 将缓冲区中的数据全部写出 
    26             bufferedOutputStream.flush();
    27  
    28             // 关闭流 
    29  
    30             bufferedInputStream.close(); 
    31             bufferedOutputStream.close(); 
    32 
    33             System.out.println("复制完成"); 
    34         } 
    35         catch(IOException e) { 
    36             e.printStackTrace(); 
    37         } 
    38     }
    39 }
     1 import java.io.*; 
     2  
     3 public class BufferedReaderWriterDemo { //利用缓冲字符流将键盘输入直接保存到文件中
     4     public static void main(String[] args) { 
     5         try { 
     6             System.out.println("输入文本,键入quit结束");
     7            // 缓冲System.in输入流
     8             BufferedReader bufReader = 
     9                 new BufferedReader(
    10                       new InputStreamReader(System.in)); 
    11            // 缓冲FileWriter字符输出流
    12             BufferedWriter bufWriter = 
    13                 new BufferedWriter(new FileWriter("Hello.txt")); 
    14  
    15             String input = null; 
    16 
    17            // 每读一行进行一次写入动作
    18             while(!(input = 
    19                       bufReader.readLine()).equals("quit")) { 
    20                 bufWriter.write(input); 
    21                  // newLine()方法写入与操作系统相依的换行字符
    22                 bufWriter.newLine(); 
    23             } 
    24  
    25             bufReader.close(); 
    26             bufWriter.close(); 
    27         } 
    28          
    29         catch(IOException e) { 
    30             e.printStackTrace(); 
    31         } 
    32     } 
    33 } 

    在字符读入缓冲流BufferedReader 中还提供了读一行的方法 readLine() 可以读取一行文本
    在字符写出缓冲流BufferedWriter 中还提供了写入一个行行分隔符的方法writeLine(),用于写出时换行

    3.按分隔符读取字串

    Scanner类有一个useDelimiter方法,可以指定分隔符(以正则表达式方式表达,如果不指定,则默认是空格),然后以这个分隔符去切割字串。

    示例设置一文本文件的内容为逗号或“ ^”分隔的字串,程序读取并显示它。 Scanncer在底层使用了BufferredReader读取数据

     1 import java.io.BufferedReader;
     2 import java.io.FileNotFoundException;
     3 import java.io.FileReader;
     4 import java.util.Scanner;
     5 
     6 public class ScannerDemo {
     7 
     8     public static void main(String[] args) {
     9         try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(
    10                 "mytext.txt")));) {
    11 
    12             scanner.useDelimiter("[,|^]");
    13             while (scanner.hasNext()) {
    14                 System.out.println(scanner.next());
    15             }
    16             System.out.println("Done!");
    17         } catch (FileNotFoundException e) {
    18 
    19             e.printStackTrace();
    20         }
    21     }
    22 
    23 }

    4.流的转换

    InputStreamReader和OutputStreamWriter可以将字节流转换为字符流。( 这类流是用于将字符转换为字节输入输出,用于操作字符文件,属于字符流的子类,所以后缀为reader,writer;前缀inputstream,outputstream;)

    示例将System.In(InputStream类型的实例)转换为字符输入流BufferedReader的实例,从而可以一次从键盘读取一行。

     1 import java.io.*;
     2 
     3 public class KeyinTest {
     4 
     5     public static void main(String[] args) {
     6         BufferedReader br = null;
     7         try {
     8             //将Sytem.in对象转换成Reader对象
     9             InputStreamReader reader = new InputStreamReader(System.in);
    10             //将普通Reader包装成BufferedReader
    11             br = new BufferedReader(reader);
    12             String buffer = null;
    13             //采用循环方式来一行一行的读取
    14             while ((buffer = br.readLine()) != null) {
    15                 //如果读取的字符串为"exit",程序退出
    16                 if (buffer.equals("exit")) {
    17                     System.out.println("程序退出……");
    18                     System.exit(1);
    19                 }
    20                 //打印读取的内容
    21                 System.out.println("输入内容为:" + buffer);
    22             }
    23         } catch (IOException ioe) {
    24             ioe.printStackTrace();
    25         } //关闭输入流
    26         finally {
    27             try {
    28                 br.close();
    29             } catch (IOException ioe) {
    30                 ioe.printStackTrace();
    31             }
    32         }
    33     }
    34 }
  • 相关阅读:
    python开发环境安装
    python文件I/O
    python字符串方法以及注释
    python列表
    php: Can't use function return value in write context
    Notice : brew install php70
    对web开发从业者的发展方向的思考
    关于微信跨号支付
    MySQL触发器写法
    MySQL慢查询日志
  • 原文地址:https://www.cnblogs.com/sengzhao666/p/9981680.html
Copyright © 2011-2022 走看看