bufferedwriter - Writing to file in Java -
first things first, novice when comes java. have set myself little project , stuck. trying write file exists, overwrites it. trying replace line contains 'maxbooks'.
here code using:
filewriter writefile = new filewriter(filelocation); bufferedreader readlines = new bufferedreader(new filereader(filelocation)); bufferedwriter writelines = new bufferedwriter(writefile); system.out.println("\n-----file begin-----"); while((finallines = readlines.readline()) != null){ if(finallines.contains("maxbooks")){ writelines.newline(); writelines.write(finallines); system.out.println("this if statement"); system.out.println(finallines); } else { filelines.add(new string(finallines)); system.out.println("this else statement"); system.out.println(finallines); } } system.out.println("------file end------");
please bear in mind have left out try , catch. please let me know how can edit text file. let me know if need more info
thanks :)
edit
sorry, should clarify. trying edit 1 line in test file, not whole text file.
final code:
filewriter writefile = new filewriter(filelocation + ".tmp", true); bufferedwriter writelines = new bufferedwriter(writefile); bufferedreader readlines = new bufferedreader(new filereader(filelocation)); system.out.println("\n-----file begin-----"); while((finallines = readlines.readline()) != null){ if(finallines.contains("maxbooks")){ writelines.write("maxbooks = " + maxbooks); writelines.newline(); system.out.println("this if statement"); system.out.println(finallines); } else { filelines.add(new string(finallines)); system.out.println("this else statement"); writelines.write(finallines); writelines.newline(); } } system.out.println("------file end------"); file2.renameto(file); writelines.close();
you overwrite file try read, bad practice. write new file, rename original file.
Comments
Post a Comment