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 而不是 Scanner 的示例)这会给你一个想法,然后你可以使用 Scanner 实现你自己的:)

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 回答