【问题标题】:Comparing content with file in Java将内容与Java中的文件进行比较
【发布时间】:2014-10-17 19:38:51
【问题描述】:

我正在尝试将一个单词作为输入并检查该单词是否存在于文本文件中。但我最终遇到了这个错误。

import java.io.*;
public class SpellingChecker {
    public static void test(String str) throws IOException{
        FileReader fr = new FileReader("wordsEn.txt");
        BufferedReader br = new BufferedReader(fr);
        int i=0,j=0,n=str.length();
        str+=' ';
        String temp="",temp2="";
        do{
            for(i=j;str.charAt(i)!=' ';i++)
                temp+=str.charAt(i);
            System.out.println(temp);
            while((temp2=br.readLine()) != null) {      
                if(temp==temp2) 
                    System.out.print("\t\t\tOK");
                else
                    System.out.print("\t\t\tWRONG");
            }
            temp="";
            j=i+1;
        }while(i<n);
        fr.close();
    }
    public static void main(String[] args) throws IOException{
        java.util.Scanner input = new java.util.Scanner(System.in);
        System.out.print("Enter string for which you want to check spelling : ");
        String strng=input.nextLine();
        test(strng);
    }
}

错误是

Exception in thread "main" java.io.FileNotFoundException: wordsEn.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:131)
    at java.io.FileInputStream.<init>(FileInputStream.java:87)
    at java.io.FileReader.<init>(FileReader.java:58)
    at SpellingChecker.test(SpellingChecker.java:5)
    at SpellingChecker.main(SpellingChecker.java:29)

【问题讨论】:

  • 您确定在FileReader中提供的路径正确吗?
  • 我把文件和.java文件放在同一个路径
  • 尝试使用文件的绝对路径(即/path/to/my/wordsEn.txt
  • 而且,如果您使用的是 Windows,请确保文件格式符合您的想法。
  • 给出错误 - 无效的转义序列(有效的是 \b \t \n \f \r \" \' \\ )

标签: java string file bufferedreader filereader


【解决方案1】:

只有文件名是不行的,创建的时候要提到文件的路径 “FileReader”对象。例如,如果路径是“C:\wordsEn.txt”,你应该写:-

FileReader fr=new FileReader(new File("C://wordsEn.txt"));

请记住,如果您使用“\”代替“//”“非法转义字符”将显示错误。 这应该可以解决它。试试看...

【讨论】:

  • 如果文件名位于同一个文件夹中,它将起作用。
【解决方案2】:

您必须将文本文件放在源目录中。

【讨论】:

  • 实际上我在 Eclipse 中工作,它在 Eclipse 中名为“src”的源目录中。至少这是我所知道的。
  • 放入“src/nameOfYourProject”
  • 其实和你刚才说的相反——nameOfYourProject/src。我想那只是一个错字。顺便说一句,我确实把它放在那个目录中。
猜你喜欢
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多