【问题标题】:Modify a specific content of a file with user defined value使用用户定义的值修改文件的特定内容
【发布时间】:2016-02-11 12:00:19
【问题描述】:

这是我当前的输出:

********MENU********
1. UNIT
2. EXIT
*********************
Select your option from 1 or 2: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1

This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify? 1
Asero/California
Asero/California
Unit Name: Iron Man
Unit Location: California
Return to menu? Select 1: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1

This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify? 
Process interrupted by user.

我想要的是将“Asero/California”修改并替换为“Iron Man/California”。

原来的输出还是:

[1] Asero/California
[2] Captain America/Pennsylvania

我想要的输出是当我修改数据时它现在应该是:

[1] Iron Man/California
[2] Captain America/Pennsylvania

我有一个 textfile = "practice.txt",这是存储数据的地方。

我还有另一个文本文件 = "tempPractice.txt",它只是用于放置临时数据。

public class Practice
{
    List<String> lines = new ArrayList<String>();

    public Practice()
    {
        try
        {
            String line = "";
            System.out.println("********MENU********");
            System.out.println("1. UNIT");
            System.out.println("2. EXIT");
            System.out.println("*********************");
            System.out.print("Select your option from 1 or 2: ");

            Scanner sc = new Scanner(System.in);
            line = sc.next();

            if(line.equals("1"))
            {
                unitMenu();
            }
            else if(line.equals("2"))
            {
                System.exit(0);
            }
            else
            {
                System.out.println("Incorrect code, please select from 1 or 2.");
                new Practice();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void unitMenu()
    {
        try
        {
            String line = "";
            System.out.println("********MENU********");
            System.out.println("1. VIEW LIST");
            System.out.println("2. BACK TO MAIN");
            System.out.println("*********************");
            System.out.print("Select your option from 1 or 2: ");

            Scanner sc = new Scanner(System.in);
            line = sc.next();

            if(line.equals("1"))
            {
                updateData();
            }
            else if(line.equals("2"))
            {
                new Practice();
            }
            else
            {
                System.out.println("Incorrect code, please select from 1 or 2.");
                unitMenu();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void updateData()
    {
        lines = new ArrayList<String>();

        File f = new File("practice.txt");
        BufferedReader bR, bR2;
        BufferedWriter bW;
        Scanner sc, sc2;
        String str = "", scanLine, oldFile, newFile, tmpFile, uName, uLoc;
        int numLine;

        try
        {
            if(!f.exists())
            {
                System.out.println("File not found!");
            }
            else
            {
                bR = new BufferedReader(new FileReader("practice.txt"));
                while((str = bR.readLine()) != null)
                {
                    lines.add(str);
                }

                System.out.println();
                System.out.println("This are the list of the units:");
                for(int i=0,j=1;i<lines.size();i++,j++)
                {
                    System.out.println( "[" + j + "] " + lines.get(i).toString());
                }
                System.out.print("What unit do you want to modify? ");

                sc = new Scanner(System.in);
                numLine = sc.nextInt();

                int count = numLine;
                --count;

                for(int k=0;k<lines.size();k++)
                {                       
                    if(count == k)
                    {
                        System.out.println(lines.get(k).toString());

                        //used for checking to know what data it returns
                        oldFile = lines.get(count).toString();
                        System.out.println(oldFile);

                        //method to replace a data --> not working/trial and error?
                        bW = new BufferedWriter(new FileWriter("tmpPractice.txt"));
                        System.out.print("Unit Name: ");
                        sc = new Scanner(System.in);
                        uName = sc.nextLine();
                        bW.write(uName);
                        bW.append('/');
                        System.out.print("Unit Location: ");
                        sc2 = new Scanner(System.in);
                        uLoc = sc2.nextLine();
                        bW.write(uLoc);
                        bW.newLine();
                        bW.close();

                        System.out.print("Return to menu? Select 1: ");
                        sc = new Scanner(System.in);
                        scanLine = sc.next();
                        if(scanLine.equals("1"))
                        {
                            unitMenu();
                        }
                        else
                        {
                            System.out.println("Error. Select only 1.");
                            updateData();
                        }
                        bR2 = new BufferedReader(new FileReader("tmpPractice.txt"));
                        while((newFile = bR2.readLine()) != null)
                        {
                            tmpFile = newFile;
                            oldFile = tmpFile;

                            bW = new BufferedWriter(new FileWriter("practice.txt", true));
                            bW.write(oldFile);
                            bW.close();
                        }
                        System.out.println(oldFile);
                        bR2.close();
                    }
                    bR.close();
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] a)
    {
        new Practice();
    }
}

我该怎么做?我应该做什么或应该在我的代码中使用什么? 有没有更简单的方法来做到这一点?任何反馈/建议/评论/帮助将不胜感激。

我还是Java的新手,我正在为自己做很多练习,我达到了可以将数据附加到带有IO的文件的地步,但是,我仍然不知道如何修改/replace 文件中的特定数据而不删除其所有内容。

请帮帮我,我真的很想了解更多。

【问题讨论】:

  • 尝试将您的示例代码缩减为minimal reproducible example
  • 我没有看到任何更改相关数据的尝试。除此之外,您似乎在读取文件 1 和写入文件 2 之间进行了更改,反之亦然(而且这似乎是逐行进行的)——这似乎很奇怪。使用调试器来单步调试您的代码并检查它是否按照您的意图执行。如果您遇到任何不知道如何解决的特定错误,请专门询问它们。
  • @Thomas,我做到了,我使用了:tmpFile = newFile; oldFile = tmpFile;但是,我不能让它工作?也许有更好的方法或有另一种方法?但我不知道怎么做。请帮忙。

标签: java unit-testing io bufferedreader bufferedwriter


【解决方案1】:

看看这个并进行相应的修改。

    public static void replaceSelected(String address) {
            try {
                String x = "t";
                System.out.println("started searching for line");
        File inputFile1 = new File(old file where line is to be updated);
        File tempFile = new File(address+"/myTempFile.txt");


        BufferedReader reader = new BufferedReader(new FileReader(old file "));

        String lineToRemove = "add line to remove as a variable or a text";
        String currentLine;

        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            String trimmedLine = currentLine.trim();
            if(trimmedLine.equals(lineToRemove) && x.contentEquals("t")) {
                x ="f";
            } else if(trimmedLine.equals(lineToRemove) && x.contentEquals("f")) {
                System.out.println("removed desired header");
                System.out.println("Line"+trimmedLine);
                continue;
            }
           FileWriter fw = new FileWriter(new file address,true);
                         BufferedWriter bw = new BufferedWriter(fw);
                         bw.write(currentLine);
                                         System.out.println(currentLine);
                          bw.write("\n");
                          bw.close();
        }
//        writer.close();
        reader.close();
         boolean success3 = (new File (old file address)).delete();
                            if (success3) {
                                System.out.println(" Xtra File deleted");

                            }
        } catch (Exception e){
}

【讨论】:

  • 对不起,我尝试调整和操作一些,但我仍然不明白如何,有没有更简单和更容易理解的?
  • [1] 阿塞罗/加利福尼亚 [2] 美国队长/宾夕法尼亚
【解决方案2】:

我已经制定了这段代码。在我的代码中,我没有使用 temp file 而是使用 arraylist 将旧值替换为新值。之后,我将 arraylist 写到文件。请参阅下面的更改代码。我只在此处包含了更改后的代码。这对我有用。

            for(int k=0;k<lines.size();k++)
            {                       
                if(count == k)
                {
                    System.out.println(lines.get(k).toString());

                    //used for checking to know what data it returns
                    oldFile = lines.get(count).toString();
                    System.out.println(oldFile);

                    System.out.print("Unit Name: ");
                    sc = new Scanner(System.in);
                    uName = sc.nextLine();
                    System.out.print("Unit Location: ");
                    sc2 = new Scanner(System.in);
                    uLoc = sc2.nextLine();
                    String replaceString = uName+"/"+uLoc;
                    lines.set(k, replaceString);
                    FileOutputStream fop = null;
                    fop = new FileOutputStream(f);
                   for(String content:lines){
                       byte[] contentInBytes = content.getBytes();
                       fop.write(contentInBytes);
                       fop.write("\n".getBytes());
                   }

                   fop.flush();
                   fop.close();

                    System.out.print("Return to menu? Select 1: ");
                    sc = new Scanner(System.in);
                    scanLine = sc.next();
                    if(scanLine.equals("1"))
                    {
                        unitMenu();
                    }
                    else
                    {
                        System.out.println("Error. Select only 1.");
                        updateData();
                    }

                }
                bR.close();
            }

您使用过 String replaceString = ...? replaceString 是值还是变量?

replaceString 是一个包含用户输入值的变量 替换文件中所需的字符串值

另一个是:lines.set(k, replaceString) -> 我也可以将它声明为 public void replaceString 吗?还是这是更简单的方法?

这里我们正在替换 arraylist(lines) 中的 indexed(k) 值 包含输入文件值,以及用户输入的值。

另外,请问一下,byte[] 有什么用,是像 charAt[] 还是更像 Tokenizer?

现在被替换的内容正在写回文件。为此我们 将字符串值转换为字节数组(byte [])并写入 使用 FileOutputStream

【讨论】:

  • 感谢您的反馈,我只是想问一些问题或澄清。你用过 String replaceString = ...? replaceString 是值还是变量?另一个是:lines.set(k, replaceString) -> 我也可以将其声明为 public void replaceString 吗?还是这是更简单的方法?还有,请问byte[]有什么用,是像charAt[]还是更像Tokenizer?
  • @Loen Seto 我已经更新了您的问题的答案。如果这对您来说很清楚,请接受答案。
  • 嗨,你的回答是对的,但是,txt 文件中有错误。每当我运行并尝试替换某些内容时,当我检查 txt 文件时,而不是有 2 个新行,现在只有 1 行,但输出仍然是 2。
  • 您好,感谢您的回答。不过,我仍然需要你的帮助。文本文件有错误。当我尝试运行这个时,输出现在是正确的,但是当我检查 txt 文件时,它现在是 1 行,而不是 2 行。例如:而不是这个:Iron Man/California newline-->Captain America/Pennsylvania 文本文件上的内容变成了这样:Iron Man/CaliforniaCaptain America/Pennsylvania...我分析了一下,我认为问题出在“\ n".getBytes()",它会在字节完全添加时添加一个新行,而是在替换的文件中添加一个空格和一个新行。
  • 请查看link,这将解决您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多