简体   繁体   English

删除和重命名文件

[英]Deleting and renaming file

So I'm trying to delete a line of data from a file, which I have successfully done by opening a new file and writing all the information that doesn't match with the data that I would like to remove. 所以我试图从文件中删除一行数据,我通过打开一个新文件并写下与我想删除的数据不匹配的所有信息来成功完成。 The problem is, after I have done that, I would like to delete my original file, and then rename the new file with excludes the information I wanted to delete, to the same name as the original file. 问题是,在我完成之后,我想删除我的原始文件,然后将新文件重命名为不包括我要删除的信息,与原始文件同名。 I have added in the code to do this, but for some reason it's not working. 我在代码中添加了这样做,但由于某种原因它不起作用。

public static void delete() throws IOException
{
    File inputFile = new File("Elements.txt");
    File tempFile = new File("myTempFile.txt");

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
    String currentLine;

    while((currentLine = reader.readLine()) != null) {
        String trimmedLine = currentLine.trim();
        if(trimmedLine.startsWith(element)) continue;
        writer.write(currentLine + System.getProperty("line.separator"));
    }
    writer.close(); 
    reader.close(); 

    inputFile.delete();
    tempFile.renameTo(inputFile);

    JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}

As you can see near the bottom, I have these lines: 正如你可以看到底部附近,我有这些线:

inputFile.delete();

tempFile.renameTo(inputFile);

These lines are meant to delete my original file(inputFile) and then rename my new file(tempFile) to the file name that the original file had. 这些行用于删除我的原始文件(inputFile),然后将我的新文件(tempFile)重命名为原始文件所具有的文件名。 After running the code however, I simply get a file called "myTempFile.txt" which has succesfully deleted the line of data that I wanted, but my original file is still present and it wasn't deleted, neither was the new file renamed to the original file. 然而,在运行代码之后,我只得到一个名为“myTempFile.txt”的文件,该文件已成功删除了我想要的数据行,但我的原始文件仍然存在且未删除,新文件也未重命名为原始文件。

Any idea why this is happening? 知道为什么会这样吗?

Use the java.nio.file API . 使用java.nio.file API This is 2015. 这是2015年。

final Path src = Paths.get("Elements.txt").toAbsolutePath();
final Path tmp = src.resolveSibling("Elements.txt.new");

try (
    final BufferedReader reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
    final BufferedWriter writer = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE_NEW);
) {
    // yadda yadda
}

Files.move(tmp, src, StandardCopyOption.REPLACE_EXISTING);

File is unreliable . File不可靠 It has always been. 它一直都是。

in such a case i would start fiddling around, reading documentation and maybe googling for a bit. 在这种情况下,我会开始摆弄,阅读文档,也许谷歌搜索一下。 But i will give you an answer, too! 但我也会给你一个答案!

inputFile.delete(); inputFile.delete();

This could go wrong, for example if you have your file opened in a text editor. 这可能会出错,例如,如果您在文本编辑器中打开了文件。 Luckily delete() returns a boolean, try checking that! 幸运的是delete()返回一个布尔值,试试看!

Also as Niels correctly mentioned File.renameTo() is quite unrelieble if you have access to Java 7 use the files.nio alternative. 此外,正如Niels正确提到的,如果您可以访问Java 7,则File.renameTo()非常难以使用files.nio替代方案。 In Java 7 you can use Files.move(Path source, Path target, CopyOption... options) 在Java 7中,您可以使用Files.move(Path source, Path target, CopyOption... options)

Docs for Java 7 Files: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html Java 7文件的文档: http//docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

But your very code works correctly for me. 但是你的代码对我来说正常。 I only change the path to the file and I make sure the file is not opened in editor 我只更改文件的路径,并确保文件未在编辑器中打开

public class NewClass {

public static void main(String[] args) {
    try {
        delete();
    } catch (IOException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void delete() throws IOException {
    File inputFile = new File("C:\\Users\\olyjosh\\Desktop\\Elements.txt");
    File tempFile = new File("C:\\Users\\olyjosh\\Desktop\\myTempFile.txt");

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
    String currentLine;

    while ((currentLine = reader.readLine()) != null) {
        String trimmedLine = currentLine.trim();
        if (trimmedLine.startsWith(element)) {
            continue;
        }
        writer.write(currentLine + System.getProperty("line.separator"));
    }
    writer.close();
    reader.close();

    inputFile.delete();
    tempFile.renameTo(inputFile);

    JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM