I want to copy the text inside a .txt File but without the last Line. So what I do is, i read the whole file (accept for the last line) with the help of a BufferedReader. Than I delete the old File and create the new File. Than I try to write the copied text inside the new File.
public class BufferedIO {
public BufferedWriter bufWriter;
public BufferedReader bufReader;
private StringBuilder inhalt;
private File file;
private String inhaltString;
private int anzZeichen;
public BufferedIO(String Speicheradresse) {
try {
file = new File(Speicheradresse); //file object gets initialized with already existing File "Stundenzettel.txt"
bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
// the next 8 are there to count how many Characters are inside the File "Stundenzettel.txt"
inhalt = new StringBuilder("");
inhaltString = bufReader.readLine();
bufReader.mark(anzZeichen);
while(inhaltString != null) {
inhalt.append(inhaltString).append("\n");
inhaltString = bufReader.readLine();
}
anzZeichen = inhalt.length();
}
catch(IOException exc) {
System.out.println("IOException... Well.. That might be a problem.");
}
}
//function where the problem is situated
public void deleteLastInput() throws IOException {
bufReader.close();
bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuilder inhaltKopie = new StringBuilder("");
String newInhalt;
//everyLine has 150 character, so as soon as there aren't more than 150 character left, the Reader stops to read the File.
while(anzZeichen > 150) {
inhaltKopie.append(bufReader.readLine()).append("\n");
anzZeichen -= 150;
}
//String newInhalt is initialized with the copied Text
newInhalt = inhaltKopie.toString();
//right here I close the bufferedReader and the BufferedWriter so that I can delete the file
bufReader.close();
bufWriter.close();
//old file gets deleted
file.delete();
//creating the new File
file.createNewFile();
//initializing the BufferedWriter + bufferedReader to the new File
bufReader = new BufferedReader(new InputStreamReader(new FileInputStream("Resources/Stundenzettel.txt")));
bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Resources/Stundenzettel", true)));
//bufWriter writes the copied Text inside the new File
bufWriter.write(newInhalt);
//not so important for this problem:
anzZeichen = newInhalt.length();
}
}
But the programm doesn't delete the old file, it just deletes everything inside this File, so that the File is empty. And also the programm doesn't write anything inside the new File.
You need to use the same file on deleteLastInput()
method
bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));