我有一个像这样的文本文件:
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
像这样:
String[] arr= null; List<String> itemsSchool = new ArrayList<String>(); 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)将是:
arr
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
这不是最佳解决方案。其他更 聪明的 答案已经给出。这仅是您当前方法的解决方案。