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メソッドのおかげで2行で実行できます。

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

BufferedReaderを使用してファイルを読み取り、readLineを文字列として使用して各行を読み取り、ループの最後にtoArrayを呼び出すArrayListに配置します。

于 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

入力ストリームまたはスキャナーを使用してファイルを1行ずつ読み取り、その行を文字列配列に格納できます。サンプルコードは次のようになります。

 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 に答える
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 に答える