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

}
4

2 回答 2

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人一样。]

你想做三件事之一。为该操作添加另一个参数,并为要添加的新行添加另一个参数。重命名另一个,因为我们并不总是删除它:

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”不匹配的行

于 2013-07-29T21:19:26.087 回答
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");
    }
}
于 2013-07-29T21:49:17.843 回答