[英]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.