从文本文件中读取第n个单词

时间:2013-11-25 20:28:11

标签: java

try 
{
    BufferedReader br = new BufferedReader(
            new FileReader(selectFile.getSelectedFile()));
    String str;

    ArrayList <String> lines = new ArrayList<String>();

    while((str = br.readLine()) != null){
        lines.add(str);
    } 
    String[] LinesArray = lines.toArray(new String[lines.size()]);

    System.out.println(lines); //Prints Array list on the screen. 

    br.close();
} 
catch(IOException e) 
{
    System.out.println("The file cannot be read");
}

如何从文件中打印n th 个字数? 例如,用户运行程序并选择带有段落的文件,我想打印出文本文件的第12和第30个单词。

我尝试过使用split,但它对我不起作用。 有什么建议吗?

2 个答案:

答案 0 :(得分:1)

Scanner input = new Scanner(new File("someText.txt"));
int count = 0;

while(input.hasNext() && count <= 30){
    count++;
    String word = input.next();

    if (count == 12){
        System.out.println(word);
    }
    if (count == 30){
        System.out.println(word);
    }
}

答案 1 :(得分:0)

似乎你已经有一个数组中的段落,我的建议是,也许你可以通过数组并继续计算空间,当空间计数器达到你想要的数字(比如11)你开始打印文字同时保持计数空间并在第29个空格后停止打印。

相关问题