(решено) Java .io.File не удаляет файл должным образом - PullRequest
0 голосов
/ 27 апреля 2020

Я хочу скопировать текст в файл .txt, но без последней строки. Поэтому я читаю весь файл (принимаю за последнюю строку) с помощью BufferedReader. Затем я удаляю старый файл и создаю новый файл. Чем я пытаюсь записать скопированный текст в новый файл.

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(); 
        }
}

Но программа не удаляет старый файл, она просто удаляет все внутри этого файла, так что файл пуст. А также программа ничего не пишет внутри нового файла.

Ответы [ 5 ]

1 голос
/ 27 апреля 2020

Следующий код загрузит содержимое файла, удалит последнюю строку и запишет измененное содержимое обратно в тот же файл. Результат - оригинальный файл, но без последней строки.

/* Required imports.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
 */
Path path = Paths.get("path", "to", "your", "file");
try {
    List<String> lines = Files.readAllLines(path);
    int count = lines.size();
    if (count > 0) {
        String removed = lines.remove(count - 1);
    }
    Files.write(path, lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
}
catch (IOException xIo) {
    xIo.printStackTrace();
}
0 голосов
/ 27 апреля 2020
Files.delete(Paths.get(your_file_name)); //should work
0 голосов
/ 27 апреля 2020

Вам нужно использовать тот же файл для deleteLastInput() метода

bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
0 голосов
/ 27 апреля 2020

попробуйте использовать bufWriter.flu sh () после bufWriter.write (newInhalt). Обратите внимание, что delete () возвращает статус того, был ли файл удален или нет. Возможно, программа не имеет надлежащего доступа для удаления файла

0 голосов
/ 27 апреля 2020

Du musst den gesamten Dateipfad angeben. Nicht nur "irgendwas.txt" sonder "c: / ..."

Необходимо указать полный путь к файлу. Вместо «thing.txt »что-то вроде« c: / ... »

...