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_stackoverflow
目录下,那么您的路径将为如下图:
FileReader reader = new FileReader(new File("C:\\test_stackoverflow\\abc.txt"));
注意双斜杠,这就是跳过斜杠的方式。
如果您的文件与 java 类位于同一目录中,则路径如下所示,不带任何斜杠
FileReader reader = new FileReader(new File("test.txt"));
假设您要读取的文件位于您的 java 类所在的上面一个文件夹 (src)
FileReader reader = new FileReader(new File("src\\test.txt"));
如果您使用的是 OSX,那么您可以在以下几行中执行某些操作
FileReader reader = new FileReader(new File("/Users/Raf/Desktop/abc.txt"));
关于java - 为什么我的代码给出 IOException(系统找不到指定的文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34153967/