Java-从文本文件创建字符串数组 [英] Java - Create String Array from text file
问题描述
我有一个像这样的文本文件:
I have a text file like this :
abc def jhi
klm nop qrs
tuv wxy zzz
我想要一个像这样的字符串数组:
I want to have a string array like :
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());
}
任何人都可以帮助我.所有的答案将不胜感激...
Anyone help me please.... All answer would be appreciated...
推荐答案
根据您的输入,您就快到了.您错过了循环中从文件中读取每一行的要点.由于您不事先知道文件中的总行数,因此请使用一个集合(动态分配的大小)来获取所有内容,然后将其转换为 String
的数组(这是您所需要的)输出).
Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String
(as this is your desired output).
类似这样的东西:
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
)将是:
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
这不是最佳解决方案.其他聪明答案已经给出.这仅是您当前方法的解决方案.
This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.
这篇关于Java-从文本文件创建字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!