[英]Reading a file from Scanner but it won't print
我有一個類讀取txt文件的一部分。 該代碼適用於某些人,但對我來說,它不會打印到控制台或附加到我的JTextArea(我的最終目標)
我只是想知道它的代碼或文件是否是問題。
public void readFiles(String fileString)
throws FileNotFoundException {
file = new File(fileString);
Scanner scanner = null;
String line = "";
// access file
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
return; // don't continue if the file is not found
}
// if more lines in file, go to next line
Boolean started = false;
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.equals("BGEND")) {
started = false;
}
if (started) // tag in the txt to locate position
{
System.out.println(line);//won't print on my console
lb1.setText(line); //attaches to a JTextArea.
window2.add(lb1); //adds to JPanel
}
if (line.equals("BGSTART")) {
started = true;
}
}
scanner.close();
}
這是我的檔案
BGSTART
Ashley the principal at Leicester,
Memorial School has been given the
task of matching some students names
to their bus numbers and departure
time, after their computer system went
down. Using only the clues that follow,
match each student to their bus number
and route to determine who goes where
and when!
Remember, as with all grid-based logic
puzzles, no option in any category will
ever be used more than once. If you get
stuck or run into a problem try the Clear
button to remove any mistakes that might
be present on the grid, or use one of your
4 hints with the Hint button to see what is
the next logical step to solve the puzzle.
BGEND
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.equals("BGSTART")) {
started = true;
}
if (line.equals("BGEND")) {
started = false;
}
if (started) // tag in the txt to locate position
{
System.out.println(line);//won't print on my console
lb1.setText(line); //attaches to a JTextArea.
window2.add(lb1); //adds to JPanel
}
}
這樣,程序首先檢查第一行是否等於“BGSTART”字符串,將布爾值設置為true並繼續執行下一個if語句並執行該代碼,只要它到達文件末尾即可。
Boolean started = false;
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.startsWith("BGSTART")) {
started = true;
continue;
}
if (line.startsWith("BGEND")) {
started = false;
break;
}
if (started) // tag in the txt to locate position
{
System.out.println(line);//won't print on my console
lb1.setText(line); //attaches to a JTextArea.
window2.add(lb1); //adds to JPanel
}
}
scanner.close();
嘗試這個。 基本上,如果你有類似的東西:
some lines of text here
BGSTART
some lines of text here
BGEND
代碼應跳過BGSTART標記之前的文本行。 遇到此標記后,布爾標志值將更改為TRUE,以使代碼知道您已開始讀取有效行,並立即跳過其余代碼以獲取下一行。 如果遇到BGEND標記,則表示結束。 所以在這種情況下,你想徹底擺脫循環。 然后,如果布爾標志設置為TRUE,則需要對從文件中讀取的文本行執行某些操作。
我認為上面的代碼完全符合您的需求。 它也適用於這樣的情況:
some lines of text here
BGSTART
some lines of text here
BGEND
some lines of text here
BGSTART
some lines of text here
BGEND
有效地只讀取BGSTART和BGEND之間的那些文本行,而不是BGEND和BGSTART之間的那些行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.