Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中仅打印文本第一行上的字符串_Java_File_Printing - Fatal编程技术网

在java中仅打印文本第一行上的字符串

在java中仅打印文本第一行上的字符串,java,file,printing,Java,File,Printing,我是java新手,希望逐字符打印文本文件中的字符串,但它只打印第一行字符串,当我在文本文件的下一行写入内容时,代码不会打印它们。有人能帮我吗。我附上下面的代码 import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; public class main { public static void main(String[] args) throws FileNotFo

我是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);
        }
    }
    
}
导入java.io.File;
导入java.util.Scanner;
导入java.io.FileNotFoundException;
公共班机{
公共静态void main(字符串[]args)引发FileNotFoundException{
char ch;
File newFile=新文件(“C:/temp/sourcecode.txt”);
扫描仪扫描文件=新扫描仪(新文件);
字符串str;
str=scanFile.nextLine();
int l=str.length();

对于(int i=0;i,您将希望使用扫描仪(而不是从nextLine()返回的字符串)。如果仔细查看,您正在读取一次文件。您的循环应如下所示:

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

发生这种情况的原因是
nextLine()
读取文件直到
Scanner.LINE\u模式
\r\n
)。 要读取整个文件,请执行以下操作:


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

 }
试试这个

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
快乐学习:)

我是java新手,希望打印文本文件中的字符串 逐字符打印,但仅打印第一行字符串

这是因为您只读取第一行。此外,您在读取该行时没有检查文件中是否有任何行,因此如果文件为空,您将收到异常。在调用
scanFile.nextLine()之前,必须始终检查if
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);
}
你们看到答案了吗?在这里你们可以找到如何读取文件的所有内容并在控制台上打印。
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);
    }
}