【问题标题】:Java - Create String Array from text file [duplicate]Java - 从文本文件创建字符串数组
【发布时间】:2012-10-12 10:38:49
【问题描述】:

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

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

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

【问题讨论】:

  • 您好,爱德华,欢迎来到 SO。如果您的问题已得到解答,请选择一个有效的答案,谢谢:)

标签: java string


【解决方案1】:

如果您使用 Java 7,由于the Files#readAllLines method,它可以分两行完成:

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

【讨论】:

  • +1 我不知道可能对小文件很方便的 readAllLines 实用程序。
  • @assylias :我试试这个,但它在字符集上显示红色下划线。我该怎么办?
  • 提供文件使用的字符集 - 通常类似于 Charset.forName("UTF-8")
【解决方案2】:

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

【讨论】:

  • 请注意,他希望每一行都是数组中的一个条目,而不是被行内的标记分解。
【解决方案3】:

根据您的输入,您就快到了。您错过了循环中从文件中读取每一行的点。由于您事先不知道文件中的总行数,因此请使用集合(动态分配的大小)来获取所有内容,然后将其转换为 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) 将是:

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

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

【讨论】:

  • 谢谢,我认为它可以工作,但在 LogCat 中,显示:错误:/text1.txt:打开失败:ENOENT(没有这样的文件或目录)
  • 您应该在当前目录中有text1.txt 输入文件(正如您在问题中所拥有的那样),否则您需要提供路径和文件名
  • 是的,我把它放在同一个文件夹中。抱歉,我忘了提到我正在开发 Android 应用程序。会和普通的 Java App 一样吗?
  • 是的,在同一个文件夹中,但最好不要将配置文件与源代码混淆。你最好创建一个文件夹并放在那里
  • 我还是发现了错误。一些教程提到了 android 的 getFileDir() 方法,以便找到文件的路径。当我使用它时,在 LogCat 中要求我将文件放入 /data/data/
【解决方案4】:

这是我生成随机电子邮件的代码,从文本文件创建一个数组。

import java.io.*;

public class Generator {
    public static void main(String[]args){

        try {

            long start = System.currentTimeMillis();
            String[] firstNames = new String[4945];
            String[] lastNames = new String[88799];
            String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
            String firstName;
            String lastName;
            int counter0 = 0;
            int counter1 = 0;
            int generate = 1000000;//number of emails to generate

            BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
            BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
            PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));


            while ((firstName = firstReader.readLine()) != null) {
                firstName = firstName.toLowerCase();
                firstNames[counter0] = firstName;
                counter0++;
            }
            while((lastName= lastReader.readLine()) !=null){
                lastName = lastName.toLowerCase();
                lastNames[counter1]=lastName;
                counter1++;
            }

            for(int i=0;i<generate;i++) {
                write.println(firstNames[(int)(Math.random()*4945)]
                        +'.'+lastNames[(int)(Math.random()*88799)]+'@'+emailProvider[(int)(Math.random()*emailProvider.length)]);
            }
            write.close();
            long end = System.currentTimeMillis();

            long time = end-start;

            System.out.println("it took "+time+"ms to generate "+generate+" unique emails");

        }
        catch(IOException ex){
            System.out.println("Wrong input");
        }
    }
}

【讨论】:

    【解决方案5】:

    您可以使用某些输入流或扫描仪逐行读取文件,然后将该行存储在字符串数组中。示例代码将是..

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

    【讨论】:

      【解决方案6】:
          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]
      

      您可以阅读有关扫描仪的更多信息here

      【讨论】:

        【解决方案7】:

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

        例子:

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

        上面的数组包含你需要的输出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-18
          • 2017-06-19
          • 1970-01-01
          • 2016-01-02
          • 1970-01-01
          • 2010-12-03
          相关资源
          最近更新 更多