Java中如何一行行地读文件 - BufferedReader Scanner

      Java中使用BufferedReader和Scanner一行行地读文件。Java中有很多一行行读文件的方法。很多使用BufferedReader简单读文件的例子,因为它提供了readLine()方法。Java 1.5中除了引入Generics, Enum和Varargs,也引入了几个新的Java类,Java API中的一个工具类Scanner,也可以一行行地读文件。虽然BufferedReader在JDK 1.1中就可以使用,但java.util.Scanner相对BufferedReader提供了更多有用的方法。Scanner有hasNextLine()和nextLine()的方法可以用来一行行地读问及那。nextLine()和readLine()类似返回String,但是Scanner有更有用的方法,如nextInt(),nextLong(),可以用来直接从文件读数字,而无需通过String到Integer的转换。Scanner是读文件相对较新的类,而BufferedReader是标准的。

      Java中一行行地读文件 - BufferedReader举例当使用FileInputStream或一些IO Reader不要忘记在finally块中关闭这个stream,以便相关的文件描述符得到释放。如果没有关闭的话,当有限资源被使用Java程序也许会内存泄露,更坏的情况是不可能打开任意新的文件。如果你正在使用Java 7你可以使用自动化的资源管理或ARM块来让Java自动化关闭那些资源。

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.logging.Level;

import java.util.logging.Logger;





public class BufferedReaderExample {   



    public static void main(String args[]) {

      

        //reading file line by line in Java using BufferedReader       

        FileInputStream fis = null;

        BufferedReader reader = null;

      

        try {

            fis = new FileInputStream("C:/sample.txt");

            reader = new BufferedReader(new InputStreamReader(fis));

          

            System.out.println("Reading File line by line using BufferedReader");

          

            String line = reader.readLine();

            while(line != null){

                System.out.println(line);

                line = reader.readLine();

            }           

          

        } catch (FileNotFoundException ex) {

            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);

        } catch (IOException ex) {

            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);

          

        } finally {

            try {

                reader.close();

                fis.close();

            } catch (IOException ex) {

                Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

  } 

  本例中我们使用BufferedReader来读一行行地文件的内容。BufferedReader需要一个InputStream(在这里是FileInputStream)和readeLine()来返回行的值,如果Stream结束则返回null。行的结束通过结束符如\n或\r

Output:

Reading File line by line using BufferedReader

first line in file

second line

third line

fourth line

fifth line

last line in file

  

    Java中一行行地读文件 - Scanner举例
    Scanner是Java 1.5中新引入的类,也有一些其他的改变,例如auto-boxing,是从console读文件优先选择的方式。因为Scanner可以从InputStream读文件,也可以从文本文件读,并提供了很多有用的方法,如nextLine()或nextInt()。

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.util.Scanner;





public class ScannerExample {

  



    public static void main(String args[]) throws FileNotFoundException  {

      

       //Scanner Example - read file line by line in Java using Scanner

        FileInputStream fis = new FileInputStream("C:/sample.txt");

        Scanner scanner = new Scanner(fis);

      

        //reading file line by line using Scanner in Java

        System.out.println("Reading file line by line in Java using Scanner");

      

        while(scanner.hasNextLine()){

            System.out.println(scanner.nextLine());

        }

      

        scanner.close();

    }   

      

}

  

Output:

Reading file line by line in Java using Scanner

first line in file

second line

third line

fourth line

fifth line

last line in file

转自:http://blog.sina.com.cn/s/blog_756e07630101j3pj.html

自测试代码:

package sina.io;



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;



/**

 * 利用Scanner读取文件

 * 

 * @author Luochengor

 *

 */

public class ScannerTest {

        

        public static void main(String[] args) {

                String basePath = null;

                String path = null;

                FileInputStream fis = null;

                Scanner scanner = null;

                try {

                        basePath = ScannerTest.class.getClassLoader().getResource("").getPath();

                        path = basePath + "sina\\io\\test.txt";

                        fis = new FileInputStream(path);

                        scanner = new Scanner(fis);

                        String line = "";

                        while (scanner.hasNext()) {

//                              line = scanner.next(); // 找到下一个空格或者换行为止

                                line = scanner.nextLine(); // 找到下一个空行为止

                                System.out.println("line : " + line);

                        }

                } catch (FileNotFoundException e) {

                        e.printStackTrace();

                } finally {

                        if (fis != null) {

                                try {

                                        fis.close();

                                } catch (IOException e) {

                                }

                        }

                }

        }

        

}

  

  

 

你可能感兴趣的:(bufferedreader)