zoukankan      html  css  js  c++  java
  • java 文件读取汇总

    概要说明:这里汇总了线上常用到的各种按行读取方法

    1、BufferedReader

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
     
    public class ReadFileLineByLineUsingBufferedReader {
     
        public static void main(String[] args) {
            BufferedReader reader;
            try {
                reader = new BufferedReader(new FileReader("/Users/test/Downloads/myfile.txt"));
                String line = reader.readLine();
                while (line != null) {
                    System.out.println(line);
                    // read next line
                    line = reader.readLine();
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    2、Scanner

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
     
    public class ReadFileLineByLineUsingScanner {
     
        public static void main(String[] args) {
            try {
                Scanner scanner = new Scanner(new File("/Users/test/Downloads/myfile.txt"));
                while (scanner.hasNextLine()) {
                    System.out.println(scanner.nextLine());
                }
                scanner.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    3、Files

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;
     
    public class ReadFileLineByLineUsingFiles {
     
        public static void main(String[] args) {
            try {
                List<String> allLines = Files.readAllLines(Paths.get("/Users/test/Downloads/myfile.txt"));
                for (String line : allLines) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    4、RandomAccessFile

    import java.io.IOException;
    import java.io.RandomAccessFile;
     
    public class ReadFileLineByLineUsingRandomAccessFile {
     
        public static void main(String[] args) {
            try {
                RandomAccessFile file = new RandomAccessFile("/Users/test/Downloads/myfile.txt", "r");
                String str;
                while ((str = file.readLine()) != null) {
                    System.out.println(str);
                }
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    bzoj3786 星系探索
    [JSOI2008]火星人
    [NOI2005]维护数列
    [POI2008]砖块Klo
    郁闷的出纳员
    [HNOI2002]营业额统计
    [BZOJ1651][Usaco2006 Feb]Stall Reservations 专用牛棚
    [BZOJ2124]等差子序列
    [BZOJ3038]上帝造题的七分钟2
    [BZOJ1711][Usaco2007 Open]Dining吃饭
  • 原文地址:https://www.cnblogs.com/liang1101/p/14788078.html
Copyright © 2011-2022 走看看