[英]java trouble reading line from file
我的代碼未從文件讀取行。 但是我不確定為什么。 初學者級Java,任何輸入都是有幫助的。
謝謝。
public class ReverseWords {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = in.nextLine();
File f = new File(fileName);
try {
Scanner input = new Scanner(f);
int n = input.nextInt();
String line = input.nextLine();
System.out.println(line);
String [] words = line.split(" ");
for(int i=0; i<words.length; i++){
System.out.println(words[i]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
沒有文件內容,我只能猜測。
nextInt()
不會更改Scanner
的行計數器,因此nextLine()
調用將返回您當前所在的其余行。 那可能不是您想要的,這就是為什么不讀取任何行的原因。
為了避免這種情況,您可以在nextInt()
之后執行額外的nextLine()
調用來顯式更改行計數器:
int n = input.nextInt();
input.nextLine();
String line = input.nextLine();
從Scanner.nextLine API文檔中:
此方法返回當前行的其余部分,但不包括最后的任何行分隔符。
我假設您有filenotfound異常。
您必須指定絕對路徑作為輸入。
drive:/sample/input.txt
首先嘗試直接從中讀取源文件
Scanner sc = new Scanner(new File("drive:/dir/file"));
或者,您可以將文件放在項目所在的位置。 [該文件夾被命名為項目名稱]在這種情況下,您只需指定“ file.extesion”作為輸入即可從該文件讀取。
但是如果文件存在:(可以檢查新的File(filename.ext).exists()),然后檢查是否有要讀取的輸入
要讀取整個文件或其他行,您應該將其放入循環中(實際上您只能讀取一行)
while(sc.hasnextLine())
{
line=sc.nextLine() //check it first and then process
//process this line for words
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.