代码之家  ›  专栏  ›  技术社区  ›  Enrique San Martín

Java:如何读取一个字符串数组的TXT文件[复制]

  •  10
  • Enrique San Martín  · 技术社区  · 15 年前

    这个问题已经有了答案:

    嗨,我想读取一个具有n行的txt文件,结果将其放入一个字符串数组中。

    4 回复  |  直到 15 年前
        1
  •  23
  •   polygenelubricants    15 年前

    使用A java.util.Scanner java.util.List .

    Scanner sc = new Scanner(new File(filename));
    List<String> lines = new ArrayList<String>();
    while (sc.hasNextLine()) {
      lines.add(sc.nextLine());
    }
    
    String[] arr = lines.toArray(new String[0]);
    
        2
  •  5
  •   Bozho    15 年前
    FileUtils.readLines(new File("/path/filename"));
    

    apache commons-io

    这会给你一个 List 属于 String . 你可以使用 List.toArray() 转换,但我建议你留下来 .

        3
  •  2
  •   JRL    15 年前

    你读过吗? the Java tutorial ?

    例如:

    Path file = ...;
    InputStream in = null;
    try {
        in = file.newInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException x) {
        System.err.println(x);
    } finally {
        if (in != null) in.close();
    }
    
        4
  •  0
  •   crazyscot    15 年前

    建立一个 BufferedReader 要从文件中读取,然后从缓冲区中提取行,但要多次。