Results 1 to 15 of 15
  1. #1
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default How to make a program that replaces each line of a file with its reverse

    Hello everyone!
    Peace be with you!

    I am trying to make a program that replaces each line of a file with its reverse. The way I want to do it will involve reading and writing a text file (IO).
    Of course the file will not be being written and read at the same time.

    I want to do it in a such way I make random text (like "how are you") in a text file and then write codes that reverse it. If I run the program for the first time, I should get a reversed text (which is, for our example, "uoy era woh"). If I run it for the second time, I should get the original text.

    Any idea of how to handle this?

    I will appreciate your support.

    Thank you.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Of course the file will not be being written and read at the same time.

    I agree. Another factor you didn't mention is that if something Bad happens (and, with I/O, Bad things will happen) you don't want to end up with a file that's neither one thing .rehtona ron

    One idea:

    * create a new (temporary) file
    * write the output to the temporary file
    * delete the original
    * rename the temporary file.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Also, it would be extremely helpful to create a method which reverses a single string for you, then overload it to work on an array list or an array.

    Read the files in, store them in an array list, pass to array list method, then write back to file. If you run into more trouble feel free to ask specific questions here.

  4. #4
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    Thank you for your sunde887!

    I would like to use args[] as an array that contains one element which is a text file. I am using Eclipse. I would make the text file an argument of the array by going to "run configurations" and then type in the name of the file.

    From there, I am kinda stuck. Can I still use your method of reversing one string first and then overload the method? Or there is an easier way to that? Thanks

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    args[] will be containing the file you are reading, however; the file can have x lines of strings, where x is unknown. Since you want to store all the info in the file, and then reverse it, and then write it, it would be helpful to read in and add the stuff to an array list.

    Java Code:
    loop
      read in a line
      split into array
      add array to array list
    end loop
    This will lead to having an array list which contains each individual string in the file.

    The reason why you overload the reverse method is for simplicity. First you create a method
    Java Code:
    public String reverse(String s){
      reverse s
      return reversed string
    }
    Finally, you will overload it to call this method on each individual item in the array list

    Java Code:
    public ArrayList<String> reverse(ArrayList<String> als)
    This is a lot to start on, try what you can and come back if you run into any problems.

  6. #6
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    Thank you again!
    I am going to post what I have done so far. I have not quite followed what you told me because I did not understand how to do it. But I hope that you can show me how I can use it in what I have done so far.

    Java Code:
    import java.io.File;
    import java.io.IOException;
    import java.io.FileReader;
    import java.io.PrintWriter;
    import java. util.Scanner;
    
    /**
       This program replaces each line of a file with its reverse
    */
    public class ReverseFile
    {
       public static void main(String[] args) throws IOException
       {
          
          String origFile = args[0]; //The array contains a text file element.
                
          File inputFile= new File(origFile);
          Scanner input= new Scanner (inputFile);
     
                
          while(input.hasNextLine())
              {
        	  String aLine= input.nextLine();
        	  
        	  aLine= new StringBuffer(aLine).reverse().toString();
        	  System.out.println(aLine);
              }
          input.close();
                
       }
    }
    I did not get what I wanted ofcourse: a reversed text to the same text file. What I got was a reversed text in the output console window of Eclipse.

    Here are my concerns:
    - How can I create an arraylist from that args[] ?
    - How will I be able to take a text from a file and output its reverse into the same file without causing any problems resulting from trying to to input and output at the same time in the same file?

    Thank you.

  7. #7
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The reason it prints to the console is because thats what you do, you never write it to the file. If you are gonna write as you read, you will need to write to a different file, delete the original file, and then replace the old file.

    Java Code:
    while(has more){
      read line
      reverse text
      write line
    }
    delete original file
    rename new file
    If you do an array list approach you can read all the information into the array list on one loop, and then write it back to the original file in reverse in another loop

    Java Code:
    create array list
    loop
      read into array list
    end loop
    reverse text in array list
    loop 
      write array list to file
    end loop
    Either way is more than suitable. I also suggest you close a stream in a finally class.
    Java Code:
    try{
      open stream
      do stuff
    }catch studd
    end try
    finally{
      try{
        close stream
      } catch exceptions
    }end finally

  8. #8
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    Thank you!
    I would like to try the second approach of using an arraylist since I do not want to change the file name. I have a question however: How do I convert my array? I have right now args[0] as an array that contains one element which is my text file.

    I appreciate

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You use the args[0] to get the file from command line, however, you don't need to get all your information from there.

    You will originally split all the information in the array up and add it to the array list.

    Java Code:
    public class Example{
      public static void main(String[] args){
        String a = "Hi this is a medium length string to test";
        ArrayList<String> strings = new ArrayList<String>();
        String[] s = a.split(" ");
        for(int i = 0; i < s.length; ++i){
          strings.add(s[i]);
        }
        //alternate approaches
        //for each loop
        for(String st : s){
          strings.add(st);
        }
        //easiest method
        strings.add(Arrays.asList(s));
    }

  10. #10
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    Thank you so much again for your helpful suggestions.

    I preferred using the first method:
    Java Code:
    String a = "Hi this is a medium length string to test";
        ArrayList<String> strings = new ArrayList<String>();
        String[] s = a.split(" ");
        for(int i = 0; i < s.length; ++i){
          strings.add(s[i]);
    BUT I am wondering how I will be able to reverse the strings that are inside the arraylist. So far when I do this :
    Java Code:
     [b]String aName [/b]= strings.add(s[i]);
    , Eclipse tells me that the type for aName is incorrect. How can I get the array in String form so that I would be able to reverse it using
    Java Code:
    aName= new StringBuffer(aName).reverse().toString();
    ?

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You could use a loop which reverses each word in the array list and writes it. Again, you can use 2 loops, a for each loop, or a regular for
    Java Code:
    for(int i = 0; i < list.size(); i++){
      String aString = list.get(i);
      reverse
      write aString to file
    }
    or, an easier approach is
    Java Code:
    for(String s : list){
      write reversed string
    }

  12. #12
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    I am sorry for keeping the same problem, Sunde887.
    If you still have a time to look at my codes, I would love to know why the aString can't be reversed. Is there anything wrong I have done?
    P.S. I have not done the writing-to-file part yet. Again thank you for your patience.

    Java Code:
    public class ReverseFile
    {
       public static void main(String[] args) throws IOException
       {
          
          String origFile = args[0]; //The array contains a text file element.
          File inputFile= new File(origFile);
        
          Scanner input= new Scanner (inputFile);
          
                
          while(input.hasNextLine())
              {
        	  String aLine= input.nextLine();
        	  
        	  ArrayList<String> strings = new ArrayList<String>();
              String[] s = aLine.split(" ");
              for(int i = 0; i < s.length; ++i){
                strings.add(s[i]);
                for(int i = 0; i < strings.size(); i++){
                	  String aString = strings.get(i);}
    
        	  
        	  aString= new StringBuffer(aString).reverse().toString();
        	  System.out.println(aString);
              }
          input.close();
                
       }
       }}

  13. #13
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You are declaring way more than you should inside the loop. You want to separate things a bit.

    First, read everything from a file, split it and add it to an array list declared outside the loop.

    Java Code:
    begin main
      declare array list of strings
      loop
        read line
        split line
        loop
          store split line in array list
        end loop
      end loop
      //Now that you are done reading everything in the file
      //the array list will contain every word in the file, use
      //it to reverse the text.
      begin loop
        extract element from array list
        reverse element
        remove element //you have to be extrmely careful here or else the
        store element    //output will be jumbled. writing would be simpler then
      end loop             //managing this

  14. #14
    Nicky55 is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    I finally got it!

    I declared the arraylist first.
    I extracted line from the text file using .nextLine()
    I then used the lines as elements of the arraylist
    I closed the file
    I created a PrintWriter object
    I then reversed the elements of the array using "for" statement as you mentioned early
    After the reversing, I then printed the reversed strings into the originial text file
    I then closed the PrintWriter object.

    Results: I had a reversed text substituting the original text. If happen to run the program again, I get the original text.

    OMG, I am exhausted!

    Many thanks to sunde887

  15. #15
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Glad to have helped it. I hope you learned something. Please mark your thread solved with the thread tools at the top of the page.

Similar Threads

  1. Replies: 1
    Last Post: 02-13-2011, 03:09 PM
  2. Replies: 8
    Last Post: 12-28-2010, 02:24 PM
  3. Replies: 4
    Last Post: 09-10-2009, 10:18 AM
  4. How to make Scanner read the same line
    By mcollins in forum New To Java
    Replies: 2
    Last Post: 03-03-2009, 06:41 AM
  5. Make a text in Jlabel down to next Line
    By hungleon88 in forum AWT / Swing
    Replies: 2
    Last Post: 12-01-2008, 11:10 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •