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

时间:2016-02-11 12:00:20

标签: 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

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

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

我已经制定了这段代码。在我的代码中,我没有使用临时文件而是使用 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) - &gt;我还可以将此声明为public void replaceString ???或者这是更简单的方法?

  

这里我们正在替换arraylist中的索引(k)值(行)   包含输入文件值,用户输入值。

另外,请问,byte []的用途是什么,是charAt []还是更像Tokenizer?

  

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