0

This is my current output:

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

What I wanted is the "Asero/California" is modified and replaced into "Iron Man/California".

The original output is still:

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

My desired output is when I modify the data it should now be:

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

I have a textfile = "practice.txt", which is where the data is stored.

I also have another text file = "tempPractice.txt", which is used just for putting a temporary data.

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

How would I do it? What should I do or what should I use in my code? Is there any simplier way to do this? Any feedback/suggestion/remarks/help would be deeply much appreciated.

I'm still new to Java, and I'm doing a lot of practice for myself, I reached up to the point where I can append a data to a file with IO, however, I still dont know how to modify/replace a specific data in the file without deleting all of its contents.

Please help me, I really want to learn more.

Faraz
  • 4,939
  • 3
  • 18
  • 57
Loen Seto
  • 31
  • 6
  • Try reducing your example code to an [mcve] – Ferrybig Feb 11 '16 at 12:02
  • I don't see any attempt to change the data in question. Besides that you seem to alter between reading file 1 and writing to file 2 and vice versa (and that seemingly on a line-by-line basis) - which seems to be really odd. Use a debugger to step through your code and check whether it does what you intend it to do. If you encounter any specific errors you don't know how to fix ask specifically about them. – Thomas Feb 11 '16 at 12:06
  • @Thomas, I did, I used: tmpFile = newFile; oldFile = tmpFile; however, I cannot make it work? Maybe there's a better way or there's another way? But I dont know how. Please help. – Loen Seto Feb 11 '16 at 12:12

2 Answers2

1

Take a look at this and modify accordingly.

    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){
}
AJAY
  • 297
  • 5
  • 18
1

I have worked out this code. In my code I have not used the temp file instead used the arraylist in to replace the old value with the new one.And After that I have write down the arraylist to the file. Please see below the changed code. I have only included the changed code here. This is working for me now.

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

You used String replaceString = ...? Is the replaceString a value or a variable??

replaceString is a variable that contains the user enterd value to replace the desired string value in the file

Another is this: lines.set(k, replaceString) -> can I also declare this as public void replaceString??? or is this the easier way?

here we are replacing the indexed(k) value in the arraylist(lines) that contains the input file values, with the user enterd value.

And also, may I ask, what is the use of byte[], is it like charAt[] or more like Tokenizer?

now the replaced content is writing back to the file. For this we are converting the string value to the byte array(byte []) and writing using the FileOutputStream

vineeth sivan
  • 480
  • 3
  • 17
  • Thanks for the feedback, I just want to ask some questions or clarifications. You used String replaceString = ...? Is the replaceString a value or a variable?? Another is this: lines.set(k, replaceString) -> can I also declare this as public void replaceString??? or is this the easier way? And also, may I ask, what is the use of byte[], is it like charAt[] or more like Tokenizer? – Loen Seto Feb 17 '16 at 02:24
  • @Loen Seto I have updated the answer for carifying your questions. If this is clear for you please accept the answer. – vineeth sivan Feb 17 '16 at 04:17
  • Hi, your answer is right, however, there are errors in the txt file.. Whenever I runs and try to replace something, when I check the txt file, instead of there are 2 new lines, it will only be 1 line now, however the output is still 2. – Loen Seto Feb 17 '16 at 11:36
  • Hi, thanks for you answer. However, i still need your help. There is an error on the text file. When I tried to run this one, the output is now correct but when I checked the txt file, instead of 2 lines, it is now 1 line. ex:Instead of this: Iron Man/California newline-->Captain America/Pennsylvania the contents on the text file becomes like this: Iron Man/CaliforniaCaptain America/Pennsylvania... I analyzed somehow, I think the problem is here "\n".getBytes()", it adds a new line whenever the bytes are fully added, but instead, it adds a space and a new line in the replaced file. – Loen Seto Feb 17 '16 at 11:41
  • please see the [link](http://stackoverflow.com/questions/24243348/how-to-write-new-line-in-java-fileoutputstream), that will solve your problem. – vineeth sivan Feb 18 '16 at 04:26