Java-从文本文件创建字符串数组[重复]

2023-12-01

我有一个像这样的文本文件:

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());
    }

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


如果您使用 Java 7,则可以用两行完成,这要归功于the Files#readAllLines method:

List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java-从文本文件创建字符串数组[重复] 的相关文章

随机推荐