如果确定文本尚不存在,如何将新文本添加到文本文件中

时间:2013-07-29 21:13:47

标签: java io

我一直在尝试创建一个“更新”,“删除”和“插入新内容”的类到文本文件中。 “更新”和“删除”部分正常工作。 “插入新内容”似乎没有做任何事情“。任何人都可以告诉我我的代码可能出错或缺失。

我没有收到任何错误报告,也没有收到错误代码。

我正在尝试将新内容写入文本文件中(如果文本文件中尚未包含此内容)。这可能类似于将用户的详细信息输入文本文件进行存储的情况,如果他是新用户的话。如果已经注册,则不会输入新数据,但他们可以编辑或删除以前存储的详细信息。

如果有人帮助他们,我会非常感激。

提前谢谢。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class EditDelete {

    static PrintWriter pw;
    static String line = null;

    public static void newEntry() {
        pw.println("A NEW ENTRY");
        pw.flush();
    }

  public static void removeLineFromFile(String file, String lineToRemove) {

    try {

      File inFile = new File("/D:/TestFile.txt/");

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return;
      }

      //Construct the new file that will later be renamed to the original filename.
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

      BufferedReader br = new BufferedReader(new FileReader(file));
      pw = new PrintWriter(new FileWriter(tempFile));

      //Read from the original file and write to the new
      //unless content matches data to be removed.
      while ((line = br.readLine()) != null) {
        if (!line.startsWith(lineToRemove)) {
          pw.println(line);
          pw.flush();
        } else if (line.startsWith(lineToRemove)) {
          pw.println("THIS GOT CHANGED" + "\n" + "\n");
          pw.flush();
        } else if (!line.startsWith(lineToRemove) && !line.startsWith(lineToRemove)) {
            newEntry();
        }
      }
      pw.close();
      br.close();

      //Delete the original file
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      }

      //Rename the new file to the filename the original file had.
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

}

2 个答案:

答案 0 :(得分:0)

这段代码没有意义:

    if (!line.startsWith(lineToRemove)) {
      pw.println(line);
      pw.flush();
    } else if (line.startsWith(lineToRemove)) {
      pw.println("THIS GOT CHANGED" + "\n" + "\n");
      pw.flush();
    } else if (!line.startsWith(lineToRemove) && !line.startsWith(lineToRemove)) {
        newEntry();
    }

看看条件:

  1. 如果不是从那开始......
  2. 如果它确实从那开始......(但这就是其他意思)
  3. 没有其他可能性,所以第三个不可能发生。 (也就是说它要么以或不是从那开头。)[但是看着它测试同样的事情的代码两次,但它真实的一次它将永远是真的。 a && a始终与a完全相同。]
  4. 你想做三件事之一。为操作的函数添加另一个参数,为要添加的新行添加另一个参数。重命名另一个,因为我们并不总是删除它:

    public static void removeLineFromFile(String file, int action, String lineToFind, String newLine) {
    

    然后按照以下方式进行测试:

    switch (action) {
    case 1:
        ... remove line
        break;
    case 2:
        ... replace line with 'newLine'
        break;
    case 3:
        ... add 'newLine' after the old line
        break;
    default:
        throw new RuntimeException("Illegal Option");
    }
    

    请务必重写与'lineToFind'

    不匹配的任何行

答案 1 :(得分:0)

试一试。它有点乱,你可以清理它。但它几乎就是你要找的东西。您可以添加一个条目,如果它存在,它不会再添加它。它也会删除一个条目就好了。查看其使用的主要方法。如果文件不存在,构造函数将处理创建文件。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileModification
{
    private File file = null;

    /**
     * Constructor
     * 
     * @param file
     */
    public FileModification(File file)
    {
        this.file = file;

        if(!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * Add an entry if it doesn't exist
     * 
     * @param entry
     * @return true if successfully added/updated
     */
    public boolean addEntry(String entry)
    {
        try
        {
            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(file.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            String line;
            boolean isDuplicate = false;
            while ((line = br.readLine()) != null)
            {
                if (line.equals(entry))
                {
                    isDuplicate = true;
                    System.out.println("Is duplicate");
                }
                pw.println(line);
                pw.flush();
            }

            if(!isDuplicate)
            {
                System.out.println("Added: " + entry);

                pw.println(entry);
                pw.flush();
            }

            pw.close();
            br.close();

            // Delete the original file
            if (!file.delete())
            {
                System.out.println("Could not delete file");
                return false;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(file))
            {
                System.out.println("Could not rename file");
                return false;
            }

            return true;
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Delete entry
     * 
     * @param entry
     * @return true if successfully deleted
     */
    public boolean deleteEntry(String entry)
    {
        try
        {
            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(file.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            String line;
            while ((line = br.readLine()) != null)
            {
                if (!line.equals(entry))
                {
                    pw.println(line);
                    pw.flush();
                }
                else
                {
                    System.out.println("Deleted: " + entry);
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!file.delete())
            {
                System.out.println("Could not delete file");
                return false;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(file))
            {
                System.out.println("Could not rename file");
                return false;
            }

            return true;
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return the file
     */
    public File getFile()
    {
        return file;
    }

    /**
     * @param file
     *            the file to set
     */
    public void setFile(File file)
    {
        this.file = file;
    }

    public static void main(String[] args)
    {
        FileModification mod = new FileModification(new File("TEST.txt"));
        mod.addEntry("NEW ENTRY1");
        mod.addEntry("NEW ENTRY2");
        mod.addEntry("NEW ENTRY3");

        mod.deleteEntry("NEW ENTRY1");
    }
}