Java – 从文本文件创建字符串数组

我有这样的文本文件:

abc def jhi klm nop qrs tuv wxy zzz 

我想要一个字符串数组,如:

 String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"} 

我试过了 :

 try { FileInputStream fstream_school = new FileInputStream("text1.txt"); DataInputStream data_input = new DataInputStream(fstream_school); BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); String str_line; while ((str_line = buffer.readLine()) != null) { str_line = str_line.trim(); if ((str_line.length()!=0)) { String[] itemsSchool = str_line.split("\t"); } } } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } 

任何人请帮助我….所有答案将不胜感激…

根据您的输入,您几乎就在那里。 你错过了循环中的点,从文件中读取每一行。 由于您没有先验知道文件中的总行数,因此使用集合(动态分配的大小)来获取所有内容,然后将其转换为String数组(因为这是您想要的输出)。

像这样的东西:

  String[] arr= null; List itemsSchool = new ArrayList(); try { FileInputStream fstream_school = new FileInputStream("text1.txt"); DataInputStream data_input = new DataInputStream(fstream_school); BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); String str_line; while ((str_line = buffer.readLine()) != null) { str_line = str_line.trim(); if ((str_line.length()!=0)) { itemsSchool.add(str_line); } } arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]); } 

那么输出( arr )将是:

 {"abc def jhi","klm nop qrs","tuv wxy zzz"} 

这不是最佳解决方案。 其他更聪明的答案已经给出。 这只是您当前方法的解决方案。

如果使用Java 7,由于Files#readAllLines方法,它可以在两行中完成:

 List lines = Files.readAllLines(yourFile, charset); String[] arr = lines.toArray(new String[lines.size()]); 

使用BufferedReader读取文件,使用readLine作为字符串读取每一行,并将它们放在ArrayList中,在循环结束时调用toArray。

您可以使用某些输入流或扫描程序逐行读取文件,然后将该行存储在String Array中。示例代码将为..

  File file = new File("data.txt"); try { // // Create a new Scanner object which will read the data // from the file passed in. To check if there are more // line to read from it we check by calling the // scanner.hasNextLine() method. We then read line one // by one till all line is read. // Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); //store this line to string [] here System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } 
  Scanner scanner = new Scanner(InputStream);//Get File Input stream here StringBuilder builder = new StringBuilder(); while (scanner.hasNextLine()) { builder.append(scanner.nextLine()); builder.append(" ");//Additional empty space needs to be added } String strings[] = builder.toString().split(" "); System.out.println(Arrays.toString(strings)); 

输出:

  [abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz] 

你可以在这里阅读更多关于扫描仪

您可以使用readLine函数读取文件中的行并将其添加到数组中。

示例:

  File file = new File("abc.txt"); FileInputStream fin = new FileInputStream(file); BufferedReader reader = new BufferedReader(fin); List list = new ArrayList(); while((String str = reader.readLine())!=null){ list.add(str); } //convert the list to String array String[] strArr = Arrays.toArray(list); 

上面的数组包含您所需的输出。