簡體   English   中英

閱讀txt文件並編寫字典

[英]reading txt file and writing a dictionary

我的目標是最終制作一個拼寫檢查器,但我需要一個字典來做到這一點。

在這里,我試圖允許用戶輸入任意數量的文本文件,只要文件名之間有空格(“ novel1.txt novel2.txt novel3.txt”)即可。

我將使用這些小說中的每個單詞,將它們寫在.dat文件中,這些文件在單獨的行上(即單詞詞典)。 但是我在Scanner read = new Scanner(new File(filenames[i]));發現文件未找到錯誤Scanner read = new Scanner(new File(filenames[i])); 即使我知道我有文件。

我什至嘗試將其放在源代碼包中以確保可以找到它。

在我的代碼的最底部是我運行的一個小測試(首先注釋掉其他代碼),盡管我可以清楚地看到我有txt文件,但它確實顯示“ war.txt不是文件”。輸入正確。

有人可以告訴我為什么Java無法看到我的txt文件,或者也許認為它不是正常文件嗎?

public static void main(String[] args) throws FileNotFoundException {

    Scanner in = new Scanner(System.in);

    System.out.println("Please enter the file names exactly.");

    String userInput = in.nextLine();
    String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually

    // takes each individual string from filenames and turns each one into the file
    // that the string should represent then adds the file's contents to my dictionary
    for(int i = 0; i < filenames.length; i++){
        Scanner read = new Scanner(new File(filenames[i]));
        String word = null;
        while(read.hasNext()){
            if(read.next().length() >= 2){
                word = read.next();
                // write word into myDict.dat
            }
            System.out.println(word);
        }
    }
    File war = new File("war.txt");
    if(!war.isFile()){
        System.out.println(war + " isn't a file.");
    }
}

我相信您以錯誤的方式做某事。 請嘗試以下示例,並將其與您的實際文件位置進行比較。

演示程序

import java.io.*;
class Demo {
    public static void main(String[] args) throws IOException {
        File war = new File("war.txt");
        if(!war.isFile()){
            System.out.println(war + " isn't a file.");
        } else {
            System.out.println(war + " is a file.");
        }
    }
}

編譯並運行它

javac Demo.java
java Demo

產量

war.txt isn't a file.

現在在同一目錄中創建war.txt

echo "foobar" > war.txt

再次運行代碼

java Demo

產量

war.txt is a file.

對於FileNotFoundException ,如果僅插入文件名,請確保文件位於類路徑中(例如,如果使用eclipse,則將文件放在項目的根文件夾中)。

對於war.txt問題,您應該這樣做:

File war = new File("war.txt");
if (!war.exists()) {
    war.createNewFile();
}
if(!war.isFile()){
    System.out.println(war + " isn't a file.");
}

這是因為當您執行File war = new File("war.txt"); 您沒有創建文件,必須使用war.createNewFile();顯式創建它war.createNewFile();

最后,在這里注意:

if(read.next().length() >= 2){
    word = read.next();
    // write word into myDict.dat
}
System.out.println(word);

您執行兩次read.next()而第二次不執行read.hasNext() 您應該這樣寫:

while(read.hasNext()){
    String next = read.next();
    if(next.length() >= 2){
        word = next;
        // write word into myDict.dat
    }
    System.out.println(word);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM