[英]only printing the string present on the first line of the text in java
我是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新手,想逐个字符地打印文本文件中存在的字符串,但它只打印第一行字符串
这是因为您只阅读了第一行。 此外,您正在阅读该行而不检查文件中是否有任何行,因此如果您的文件为空,您将收到异常。 在调用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);
}
}
您将需要使用扫描仪(而不是从 nextLine( 重新调整的字符串)。如果仔细观察,您正在阅读您的文件一次。您的循环应如下所示:
while(scanFile.hasNextLine()){
String line = scanFile.nextLine();
}
hasNextLine 上的JavaDoc API
发生这种情况是因为nextLine()
读取文件直到Scanner.LINE_PATTERN
(在您的情况下为\\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();
快乐学习:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.