为什么我的代码给出 IOException(系统找不到指定的文件)?

Why is my code giving IOException (System could not find the file specified)?

public static void update(String fileName, String idType, String id, String updatedData[] ) throws Exception{

    char fileOutput[];
    String wholeData;
    String tkn, idtp, idf;      

    File myFileU  = null;
    File tempFile = null;
    FileReader finU = null;
    FileWriter fwU = null;
    Scanner frU = null;



    try{

        finU = new FileReader(myFileU = new File("\" +fileName + ".txt"));
        fileOutput = new char[(int) myFileU.length()];
        finU.read(fileOutput);
        finU.close();

        //System.out.println(myFileU.getCanonicalPath());

        tempFile = new File("temp.txt");
        tempFile.createNewFile();
        fwU = new FileWriter(myFileU, false);


         wholeData = new String(fileOutput);

        frU = new Scanner(wholeData);

        frU.useDelimiter(";");

        while(frU.hasNext()){   
            idtp = frU.next();
            idf = frU.next();
            if(idtp.equals(idType) && idf.equals(id)){
                fwU.write( ";" + idType + ";" + id);
                for(int i=0; i< updatedData.length; i++){
                    fwU.write(";" + updatedData[i]);

                }
                fwU.write(";" + System.lineSeparator());

                frU.nextLine();
            }
            if(!idf.equals(id))
            fwU.write(";" + idtp + ";" + idf);
            tkn = frU.nextLine();
            fwU.write(tkn);
            fwU.write(System.lineSeparator());
            if(idf.equals(autoSerial(fileName, idType)))
                break;
        }

        fwU.flush();
        fwU.close();


        }
    catch(IOException e){
        System.out.println("error in opening the file U " + e);     
    }
    finally{

    }
}

上述方法是为了覆盖它正在读取的文件。它应该做的是从文件中读取,用更新的数据替换用户指定的记录并用更新的数据覆盖文件,但它不会覆盖文件而是在文件末尾附加更新的记录和给出(尽管如果我将数据保存到一个单独的文件中,它会将更新的数据正确地保存到它):

java.io.FileNotFoundException: \Schedules.txt (The system cannot find the file specified)

当文件存在并且它也从中读取了数据?有什么线索吗?我是 Java 的新手!

您的问题显然与使用 Java 打开文件有关。您似乎对文件路径感到困惑。以下是如何使用不同位置等打开文件的示例。

假设您的文件名为 abc.txt 并且位于 C:\ 驱动器 test_Whosebug 目录下,那么您的路径如下所示:

FileReader reader = new FileReader(new File("C:\test_Whosebug\abc.txt")); 

注意双斜线,这是您跳过斜线的方式。

如果您的文件与 java class 在同一目录下,则路径如下所示,没有任何斜杠

FileReader reader = new FileReader(new File("test.txt")); 

假设您要阅读的文件是 (src) 上面的一个文件夹,您的 java class 就是

FileReader reader = new FileReader(new File("src\test.txt"));

如果您使用的是 OSX 那么您可以在下面几行中做一些事情

FileReader reader = new FileReader(new File("/Users/Raf/Desktop/abc.txt"));