找不到指定的文件?

时间:2018-09-24 19:00:39

标签: java file java-io

我失去理智了吗?我的BufferedReader找不到指定的文件,但是我绝对确定我具有正确的路径(我已经检查了很多遍,逐步执行...我不知道发生了什么事。)

这是我的代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


/**
* Code for E11.8. Searches all files specified on the command line and 
prints out all lines     
containing a specified word.
* @author - Matthew Arnold
*/
public class Find {
/**
  Searches file for a word, prints out all lines containing that word.
  @param wordToFind the word to find
  @param filename the filename for the file to search
*/
public static void findAndPrint(String wordToFind, String fileName)throws IOException{

   BufferedReader br = new BufferedReader(new FileReader(fileName));

   ArrayList<String> stringsFromFile = new ArrayList<>();

   while(br.ready()) {
       stringsFromFile.add(br.readLine());
   }

   for(String s : stringsFromFile) {
       if(s.contains(wordToFind))
           System.out.println(s);
   }

   br.close();
}

 /**
  First argument of the main method should be the word to be searched
  For other arguments of the main method, store the file names to be examined
*/
public static void main(String[] args)
{
   String fileName = System.getProperty("user.home") + "\\Desktop\\mary.txt";
  System.out.println(fileName);


  try {
        findAndPrint("lamb", fileName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

 }
}

也许另一双眼睛可以看到我不是。任何帮助是极大的赞赏。谢谢。

编辑-添加了推荐的测试行并包括了堆栈跟踪:

更新的代码(在主目录中):

 public static void main(String[] args)
 {
   String fileName = System.getProperty("user.home") + 
 "\\Desktop\\mary.txt";
  System.out.println(fileName);


  try {
        System.out.println(new File(fileName).getAbsolutePath());
        findAndPrint("lamb", fileName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

 }
}

输出:

C:\Users\Matthew\Desktop\mary.txt
C:\Users\Matthew\Desktop\mary.txt
java.io.FileNotFoundException: C:\Users\Matthew\Desktop\mary.txt (The 
system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at Find.findAndPrint(Find.java:21)
at Find.main(Find.java:50)

1 个答案:

答案 0 :(得分:2)

我认为问题可能出在路径分隔符上,您可以使用File.separator并执行类似的操作:

  public static void main(String[] args)
  {
     String fileName = String.join(File.separator,System.getProperty("user.home"),"Desktop","mary.txt");
    System.out.println(fileName);

    try {
        findAndPrint("lamb", fileName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}