java:如何将txt文件读取到字符串数组
嗨我想读取带有N行的txt文件,结果将其放入字符串数组中。
使用java.util.Scanner
和java.util.List
。
Scanner sc = new Scanner(new File(filename)); List lines = new ArrayList (); while (sc.hasNextLine()) { lines.add(sc.nextLine()); } String[] arr = lines.toArray(new String[0]);
FileUtils.readLines(new File("/path/filename"));
来自apache commons-io
这将为您提供一个String
List
。 您可以使用List.toArray()
进行转换,但我建议继续使用List
。
你读过Java教程吗?
例如:
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(); }
设置BufferedReader
以从文件中读取,然后多次从缓冲区中拾取行。