1

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

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

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

4

7 回答 7

11

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

List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
于 2012-10-12T10:40:55.360 回答
2

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

于 2012-10-12T10:40:02.697 回答
1

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

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

于 2012-10-12T11:06:38.503 回答
1

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

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");
        }
    }
}
于 2019-05-24T07:28:14.703 回答
0
    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]

您可以在此处阅读有关扫描仪的更多信息

于 2012-10-12T10:44:32.573 回答
0

您可以使用 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);

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

于 2012-10-12T11:13:39.847 回答
0

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

 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();
        }
于 2012-10-12T10:41:51.417 回答