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:\
下的drive中,test_stackoverflow
那么您的路径将如下所示:
FileReader reader = new FileReader(new File("C:\\test_stackoverflow\\abc.txt"));
注意双斜杠,这就是您跳过斜杠的方式。
如果文件与Java类位于同一目录中,则路径如下所示,没有任何斜杠
FileReader reader = new FileReader(new File("test.txt"));
假设您希望读取的文件位于(src)上方的一个文件夹中,那么您的Java类就是
FileReader reader = new FileReader(new File("src\\test.txt"));
如果您使用的是OSX,则可以在以下几行中进行操作
FileReader reader = new FileReader(new File("/Users/Raf/Desktop/abc.txt"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句