我試圖讓 Java 從檔案中讀取文本,以便可以將文本轉換為一系列 ascii 值,但目前它似乎只是讀取和檢索 txt 檔案的第一行。我知道這是因為輸出比檔案中的文本短得多。
檔案中的文本如下:
AD Mullin Sep 2014 https://hellopoetry.com/poem/872466/prime/
Prime
Have you ever thought deeply about Prime numbers?
We normally think of prime as something unbreachable
In base ten this is most likely true
But there are other languages that might be used to break down numbers
I'm no theorist but I have my theories
What was behind the Big Bang?
Prime
If impermeable ... then the Big Bang never happened
And any good programmer worth a lick of salt, always leaves a back door
So, I bet there are some Prime numbers out there that are permeable, otherwise ...
We wouldn't be the Children of the Big Bang
我認為因為每行文本之間都有一個空行,所以程式只讀取第一行,然后當它看到它后面沒有行時停止,但實際上是 2 行。
這是我寫的代碼:
package poetry;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class poetry {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Below try catch block reads file text and encodes it.
try {
File x = new File("/Users/jordanbendon/Desktop/poem.txt");
Scanner sc = new Scanner(x);
//Right below is where I think the issue lies!
while(sc.hasNextLine()) {
String lines = sc.nextLine();
char[] stringArray = lines.toCharArray();
String result = "";
for (int i = 0; i < lines.length(); i ) {
int ascii = lines.codePointAt(i);
if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
ascii = 15;
result = Integer.toString(ascii);
} else {
result = stringArray[i];
}
}
System.out.println(result);
//Try catch block here creates a new file.
try {
File myObj = new File("/Users/jordanbendon/Desktop/EncryptedMessage.txt");
File s = myObj;
if (myObj.createNewFile()) {
System.out.println("File created: " myObj.getName());
} else {
System.out.println("File already exists.");
break;
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//Try catch block here writes the new encrypted code to the newly created file.
try {
FileWriter myWriter = new FileWriter("/Users/jordanbendon/Desktop/EncryptedMessage.txt");
myWriter.write(result);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}}
catch(FileNotFoundException e) {
System.out.println("error");
}
}
}
我已經在我認為問題所在的代碼中發表了評論。第一個 while 條件使用 hasNextLine() 檢查是否有下一行,我嘗試使用 ReadAllLines() 方法,但它表示該方法對于型別掃描器是未定義的。
如何讓程式讀取和檢索整個文本檔案而不是第一行?
謝謝!
uj5u.com熱心網友回復:
要讀取整個輸入流:
Scanner sc = new Scanner(x).useDelimiter("\\A");
然后只是:
String entireInput = sc.next();
這通過將標記分隔符設定為所有輸入的開始來作業,當然在讀取任何位元組后都不會遇到,因此“下一個”標記是整個輸入。
uj5u.com熱心網友回復:
對于每次執行,您檢查硬編碼檔案名是否已創建或已存在。如果它已經存在,你碰巧打破了阻止執行進行的回圈。 https://www.javatpoint.com/java-break
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483064.html
上一篇:沒有匯入處理檔案的時間很長
