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{
}
}
The above method is meant to overwrite the file it is reading from. What it is supposed to do is read from the file, replace the record specified by the user with updated data and overwrite the file with updated data, but it doesn't overwrite the file instead appends the updated record at the end of the file and gives (though if I save the data to a separate file it saves the updated data correctly to it):
java.io.FileNotFoundException: \Schedules.txt (The system cannot find the file specified)
While the file is there and it has read data from it too? Any clue? I'm new to Java!