在java中,我需要读取一个文本文件,然后将其输出到控制台,每次输出一个单词,以空格分隔

在java中,我需要读取一个文本文件,然后将其输出到控制台,每次输出一个单词,以空格分隔,java,console,text-files,whitespace,bufferedreader,Java,Console,Text Files,Whitespace,Bufferedreader,到目前为止,我有以下代码。编码对我来说是一种新的爱好,我还不是初学者。为了读取文本文件,我从stackoverflow复制并粘贴了它 BufferedReader r = new BufferedReader( new FileReader( "test.txt" ) ); String s = "", line = null; while ((line = r.readLine()) != null) { s +=

到目前为止,我有以下代码。编码对我来说是一种新的爱好,我还不是初学者。为了读取文本文件,我从stackoverflow复制并粘贴了它

    BufferedReader r = new BufferedReader( new FileReader( "test.txt" ) );
    String s = "", line = null;
    while ((line = r.readLine()) != null) {
        s += line;
    }
     
然后这是我从一个网站上找到的,一次打印一个单词

       int i;          // Position in line, from 0 to line.length() - 1.
       char ch;        // One of the characters in line.
       boolean didCR;  // Set to true if the previous output was a carriage return.
       
       
       System.out.println();
       didCR = true;
       
       for ( i = 0;  i < s.length();  i++ ) {
          ch = s.charAt(i);
          if ( Character.isLetter(ch) ) {
             System.out.print(ch);
             didCR = false;
          }
          else {
             if ( didCR == false ) {
                System.out.println();
                didCR = true;
             }
          }
          
       }
       
       System.out.println();  // Make sure there's at least one carriage return at the end.
inti;//在行中的位置,从0到行。长度()-1。
char ch;//一行中的一个字符。
布尔didCR;//如果上一个输出是回车,则设置为true。
System.out.println();
didCR=真;
对于(i=0;i
我真的很想输出文本文件,一次输出一个单词,用空格,这样可以包含逗号和句点等字符。请帮忙

这是有效的:

import java.io.*;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
        String s = "";
        String line = "";
        while((line = reader.readLine()) != null){
            s = s + line + "\n";
        }
        reader.close();
        s= s + " ";
        String word = "";
        char c = 0;
        for(int i= 0 ;i<s.length();i++){
            c = s.charAt(i);
            if(c == ' ' || c=='\n' || c=='\t' || c =='\r' || c=='\f' ){
                System.out.print(word.length()!=0?(word + "\n"):"");
                word = "";
            }else{
                word = word + c;
            }
        }
    }
}
输出:

hello world, this is a code.
hello
world,
this
is
a
code.

读取文件几乎已经正确,只需添加打印文字:

BufferedReader r = new BufferedReader( new FileReader( "test.txt" ) ); //create a buffer to read the file
String line;
while ((line = r.readLine()) != null) { //read each line one-by-one
    String[] words = line.split("\\s+"); //split at whitespace, the argument is a regular expression
    for( String word : words ) {
       //skip any empty string, see explanation below
       if( word.isEmpty() ) {
         continue;
       }

       //option 1: print each word on a new line
       System.out.println(word);

       //option 2: print words of a line still on one line
       System.out.print(word + " ");
    }

    //option 2: switch to a new output line
    System.out.println();
}
注意:使用选项1或2获得所需的输出

word.isEmpty()上的单词

即使我们使用
split(\\s+”)
在较长的空白序列上进行分割,您仍然可以在结果数组中得到空字符串。原因是,如果一行以空格开头,例如
a
,您将得到数组
[“”,“a”]
,并且您可能不想打印第一个空字符串-因此我们选中并跳过这些

拆分(\\s+”
上的一个单词:

该参数是一个正则表达式,
“\\s+”
表示表达式
\s
\
需要在Java字符串中转义,因此我们添加了另一个反斜杠)

\s
是一个字符类,表示“任何空白”,包括空格、换行符、回车等。末尾的
+
是一个量词,表示“一个或多个”,也用于拆分较长的空白序列。如果不添加,
ab
(3个空格)的输入将导致
[“A”,“u”,“u”,“B”]


如果只想在空格上拆分,请使用
“+”

作为其他答案的替代方案,下面是一个使用Java 8流的简洁解决方案:

Pattern word=Pattern.compile(\\s+);
try(streamlines=Files.lines(path.get(“test.txt”)、Charset.defaultCharset()){
lines.flatMap(line->word.splitAsStream(line).filter(s->!s.isEmpty())
.forEachOrdered(System.out::println);
}

如果不想使用Java8流,请使用搜索结果

正如我在早些时候所说:


如果你想用空格代替非字母,只需替换为

这是问题的代码,有了这个变化

我还修复了两个地方的新线问题。看看你能不能找到哪里

String s=”“;
try(BufferedReader r=newbufferedreader(newfilereader(“test.txt”)){
弦线;
而((line=r.readLine())!=null){
s+=第+'\n'行;
}
}
布尔didCR=真;
对于(int i=0;i
欢迎来到SO。作为一个初学者,你绝对不应该只复制代码,而应该试着去理解它。查看每个JDK类所附带的JavaDocs,以了解这些方法的作用。也就是说,第二个代码看起来非常复杂,一次只打印一个单词。第一个逐行读取文件的代码段是可以的,只是不要将该行添加到字符串中,而是将其添加到空白处,并使用内部循环在新行上打印每个单词(
System.out.println(word)
)。如果希望按空格而不是按非字母打印单词,只需替换为。第一个代码段上的一个注释:
s+=line稍后在尝试打印
s
中的单个单词时可能会导致问题。假设文件的格式如下:
第一行\n第二行
。阅读文件时,你会得到
第一行
第二行
,但是仅仅将它们连接起来就会得到
第二行
(注意
第一行
后面缺少空格)。我投票结束这个问题,因为它并不表示遇到了实际问题。可能更适合这个问题。谢谢,我没想到会有这么多帮助。虽然所有的答案都很有帮助,但我还是选择了我觉得最有帮助的答案。这个社区非常有帮助,我非常感谢所有的提示。