2

私はこのコードを持っています:

        Scanner input = new Scanner(System.in);
        System.out.println("Enter file name: ");
        File file = new File(input.nextLine());
        if (file.length() == 0) {
            System.out.println("The input file is empty.");
            System.exit(1);
        }

ユーザーが入力したファイルを読み取り、それが空かどうかを確認します。これは非常に単純です。

私がやりたいことは、このファイルの各単語を、各単語、句読点、およびすべてを含む文字列配列に入れることです (アポストロフィまたはダッシュが単語として含まれます)。どうすればいいですか?

ファイルの内容は次のようになると想定しています。

it's
Stop

the

malformed yes-man

リターンまたはスペースで区切られたランダムな単語。

あなたの助けに感謝します:)

4

2 に答える 2

3

これを確認してください(スキャナーではなくBufferedReaderを使用した例)これによりアイデアが得られ、スキャナーを使用して独自に実装できます:)

import java.io.*;
import java.util.*;

public class ReadFile
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter file name");
        String fileName = br.readLine();
        File file = new File(fileName);
        if(file.length() == 0)
        {
            System.out.println("File is empty");
        }
        else
        {
            BufferedReader fr = new BufferedReader(new FileReader(file));
            ArrayList<String> words = new ArrayList<String>();
            String[] line;
            String str;
            while((str=fr.readLine()) != null)
            {
                line = str.split(" ");
                for(String word : line)
                    words.add(word);
            }

            // Printing the content of words
            for(String word : words)
                System.out.println(word);
        }
    }
}
于 2013-03-12T03:48:14.973 に答える
0
String[] words = input.split("(?s)\\s+");
于 2013-03-12T03:33:23.823 に答える