java - 使用用户定义的值修改文件的特定内容

标签 java unit-testing io bufferedreader bufferedwriter

这是我当前的输出:

********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

我有一个文本文件=“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将数据附加到文件的程度,但是,我仍然不知道如何修改/替换文件中的特定数据而不删除其所有内容。

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

最佳答案

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

    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){
}

关于java - 使用用户定义的值修改文件的特定内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35338783/

相关文章:

java - Android按钮图片抖动动画

java - mockito 验证与 ArgumentCaptor 的交互

c# - 如何实现XUnit描述性Assert消息?

c++ - 如何从 Init 强制 gtest 将报告写入 xml

java - Java中的基本输入和输出

java - 提高 IO 性能和速度

java - 如何找到给定字符串中的每个回文子串并在一秒钟内返回出现值

java - Java 文件名中应该或必须

io - 在 Julia 中设置多个 I/O 缓冲区的最佳方法是什么?

java - 在 url 中隐藏 servlet 名称