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

如何解决在java中,我需要读取一个文本文件,然后将其输出到控制台,以空格分隔

到目前为止,我有以下代码。编码对我来说是一个新的爱好,我还不如初学者。我从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.

我真的很想输出文本文件,一次一个单词,一个空格,以便包含逗号和句点等字符。请帮忙!

解决方法

这有效:

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;
            }
        }
    }
}

test.txt 的内容:

hello world,this is a code.

输出:

hello
world,this
is
a
code.
,

作为其他答案的替代方案,这里有一个使用 Java 8 Streams 的简洁的解决方案:

Pattern word = Pattern.compile("\\s+");
try (Stream<String> lines = Files.lines(Paths.get("test.txt"),Charset.defaultCharset())) {
    lines.flatMap(line -> word.splitAsStream(line).filter(s -> ! s.isEmpty()))
         .forEachOrdered(System.out::println);
}

如果您不想使用 Java 8 Stream,请使用您的搜索结果。

正如我之前在 comment 中所说:

如果您想要逐个空格而不是逐个非字母的单词,只需将 Character.isLetter(ch) 替换为 ! Character.isWhitespace(ch)

这里是问题中的代码,并进行了更改。

我还在两个地方修复了换行问题。看看你能不能找到哪里。

String s = "";
try (BufferedReader r = new BufferedReader(new FileReader("test.txt"))) {
    String line;
    while ((line = r.readLine()) != null) {
        s += line + '\n';
    }
}

boolean didCR = true;
for (int i = 0; i < s.length(); i++) {
    char ch = s.charAt(i);
    if (! Character.isWhitespace(ch)) {
        System.out.print(ch);
        didCR = false;
    } else {
        if (didCR == false) {
            System.out.println();
            didCR = true;
        }
    }
}
if (didCR == false) {
    System.out.println();
}
,

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

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"],你可能不想打印第一个空字符串 - 所以我们检查并跳过那些。

关于split("\\s+")的一句话:

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

\s 是一个表示“任意空格”的字符类,包括空格、换行符、回车等。最后的 + 是一个表示“一个或多个”的量词,用于分割在更长的空白序列上也是如此。如果您不添加 A B(3 个空格)的输入将导致 ["A","","B"]

如果您只想分割空格,请使用 " +"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-