【问题标题】:only printing the string present on the first line of the text in java只打印java中文本第一行上的字符串
【发布时间】:2020-10-16 20:17:23
【问题描述】:

我是 java 新手,想逐个字符打印文本文件中存在的字符串,但它只打印第一行字符串,当我在文本文件的下一行写一些东西时,代码不会打印它们。有人可以帮助我吗?我附上下面的代码!

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class main {
    
    public static void main(String[] args) throws FileNotFoundException {
        char ch;
        
        File newFile = new File("C:/temp/sourcecode.txt");
        Scanner scanFile = new Scanner(newFile);
        
        String str;
        str = scanFile.nextLine();
        int l = str.length();
        for(int i =0; i<l ; i++) {
            ch = str.charAt(i);
            System.out.println(ch);
        }
    }
    
}

提前谢谢你!

【问题讨论】:

  • 你看到this的回答了吗。在这里您可以了解如何读取文件的所有内容并在控制台上打印。

标签: java file printing


【解决方案1】:

我是 java 新手,想打印文本文件中的字符串 一个字符一个字符,但它只打印第一行字符串

这是因为您只阅读第一行。此外,您正在阅读该行而不检查文件中是否有任何行,因此如果您的文件为空,您将收到异常。在调用 scanFile.nextLine() 从文件中读取一行之前,您必须始终检查是否为 scanFile.hasNextLine()

为了对每一行重复这个过程,你需要一个循环,最自然的循环是while循环。因此,您需要做的就是输入以下代码:

String str;
str = scanFile.nextLine();
int l = str.length();
for (int i = 0; i < l; i++) {
    ch = str.charAt(i);
    System.out.println(ch);
}

进入while循环块如下图:

while (scanFile.hasNextLine()) {
    String str;
    str = scanFile.nextLine();
    int l = str.length();
    for (int i = 0; i < l; i++) {
        ch = str.charAt(i);
        System.out.println(ch);
    }
}

【讨论】:

    【解决方案2】:

    您将希望使用扫描仪(而不是从 nextLine() 重新调整的字符串。如果您仔细观察,您正在阅读您的文件一次。您的循环应该如下所示:

    while(scanFile.hasNextLine()){
      String line = scanFile.nextLine();
    }
    

    hasNextLine 上的 JavaDoc API

    【讨论】:

      【解决方案3】:

      这是因为nextLine() 读取文件直到Scanner.LINE_PATTERN(在您的情况下为\r\n)。 读取整个文件:

      
      while (scanFile.hasNextLine()){
        str = scanFile.nextLine();
        //your code here
      
       }
      

      【讨论】:

        【解决方案4】:

        试试这个。

        File file = new File("/my/location");
        String contents = new Scanner(file).useDelimiter("\\Z").next();
        

        学习愉快:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-15
          • 2015-04-25
          • 1970-01-01
          • 1970-01-01
          • 2014-03-16
          • 1970-01-01
          相关资源
          最近更新 更多