将文本文件内容逐行存储到数组中

所有,我现在面临的问题是不知道将文本文件中的内容存储到数组中。 情况就像,文本文件内容:

abc1 xyz2 rxy3 

我希望将它们逐行存储到数组中,这可能吗? 我的期望是这样的:

 arr[0] = abc1 arr[1] = xyz2 arr[2] = rxy3 

我尝试过类似的东西,但似乎对我不起作用。 如果有人能帮助我,真的非常感谢。

代码是:

 BufferedReader in = new BufferedReader(new FileReader("path/of/text")); String str; while((str = in.readLine()) != null){ String[] arr = str.split(" "); for(int i=0 ; i<str.length() ; i++){ arr[i] = in.readLine(); } } 

我建议使用ArrayList ,它处理动态大小调整,而数组需要预先定义的大小,你可能不知道。 您始终可以将列表转换回数组。

 BufferedReader in = new BufferedReader(new FileReader("path/of/text")); String str; List list = new ArrayList(); while((str = in.readLine()) != null){ list.add(str); } String[] stringArr = list.toArray(new String[0]); 

最简单的解决方案:

 List list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8); String[] a = list.toArray(new String[list.size()]); 

请注意,java.nio.file.Files从1.7开始

这应该有效,因为它使用List,因为您不知道文件中将有多少行,并且它们可能稍后更改。

 BufferedReader in = new BufferedReader(new FileReader("path/of/text")); String str=null; ArrayList lines = new ArrayList(); while((str = in.readLine()) != null){ lines.add(str); } String[] linesArray = lines.toArray(new String[lines.size()]); 

只需使用Apache Commons IO

 List lines = IOUtils.readLines(new FileInputStream("path/of/text")); 

你需要为你的情况做这样的事情: –

 int i = 0; while((str = in.readLine()) != null){ arr[i] = str; i++; } 

但请注意,应根据文件中的条目数正确声明arr

建议: –使用List代替(请查看@Kevin Bowersoxpost)

JAVA 8:

 Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList()); 

当你执行str = in.readLine()) != null你将一行读入str变量,如果它不是null,则执行while块。 您不需要再次在arr[i] = in.readLine();读取该行arr[i] = in.readLine(); 。 当您不知道输入文件的确切大小(行数)时,也使用列表而不是数组。

 BufferedReader in = new BufferedReader(new FileReader("path/of/text")); String str; List output = new LinkedList(); while((str = in.readLine()) != null){ output.add(str); } String[] arr = output.toArray(new String[output.size()]); 

尝试这个:

 String[] arr = new String[3];// if size is fixed otherwise use ArrayList. int i=0; while((str = in.readLine()) != null) arr[i++] = str; System.out.println(Arrays.toString(arr)); 

您可以使用此完整代码来解决您的问题。 有关更多详细信息,您可以在appucoder.com上查看

 class FileDemoTwo{ public static void main(String args[])throws Exception{ FileDemoTwo ob = new FileDemoTwo(); BufferedReader in = new BufferedReader(new FileReader("read.txt")); String str; List list = new ArrayList(); while((str =in.readLine()) != null ){ list.add(str); } String[] stringArr = list.toArray(new String[0]); System.out.println(" "+Arrays.toString(stringArr)); } } 

建议使用Apache IOUtils.readLines。 见下面的链接。

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html