Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file, reverse the order, and write reverse order

Like a similar project I made, this project is reading characters from a txt file, reversing the order of the string and rewriting it to another txt file. But it keeps outputting my exception of "Something went wrong". Can anyone help me fix what is going wrong?

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ReverseFile
{
    public static void main(String[] args) throws IOException
       {
          try{
          String source = args[0];
          String target = args[1];

          File sourceFile=new File(source);

          Scanner content=new Scanner(sourceFile);
          PrintWriter pwriter =new PrintWriter(target);

          while(content.hasNextLine())
          {
             String s=content.nextLine();
             StringBuffer buffer = new StringBuffer(s);
             buffer=buffer.reverse();
             String rs=buffer.toString();
             pwriter.println(rs);
          }
          content.close();    
          pwriter.close();
          System.out.println("File is copied successful!");
          }

          catch(Exception e){
              System.out.println("Something went wrong");
          }
       }
}

So here is the information from the stacktrace:

java.lang.ArrayIndexOutOfBoundsException: 0
    at ReverseFile.main(ReverseFile.java:36)
like image 624
Elizabeth Turner Avatar asked Jan 24 '26 20:01

Elizabeth Turner


1 Answers

i am not so sure about your environment, and how long the text might be. and i am also not so sure why you need a scanner?

anyway, here's my take on the problem, hope this helps you :)

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;


public class Reverse {

    public static void main(String[] args) {

        FileInputStream fis = null;
        RandomAccessFile raf = null;

        // by default, let's use utf-8
        String characterEncoding = "utf-8";

        // but if you pass an optional 3rd parameter, we use that
        if(args.length==3) {
            characterEncoding = args[2];
        }

        try{

            // input file
            File in = new File(args[0]);
            fis = new FileInputStream(in);

            // a reader, because it respects character encoding etc
            Reader r = new InputStreamReader(fis,characterEncoding);

            // an outputfile 
            File out = new File(args[1]);

            // and a random access file of the same size as the input, so we can write in reverse order 
            raf = new RandomAccessFile(out, "rw");
            raf.setLength(in.length());

            // a buffer for the chars we want to read 
            char[] buff = new char[1];

            // keep track of the current position (we're going backwards, so we start at the end)
            long position = in.length(); 

            // Reader.read will return -1 when it reached the end.
            while((r.read(buff))>-1) {

                // turn the character into bytes according to the character encoding
                Character c = buff[0];
                String s = c+"";
                byte[] bBuff = s.getBytes(characterEncoding);

                // go to the proper position in the random access file
                position = position-bBuff.length;
                raf.seek(position);

                // write one or more bytes for the character
                raf.write(bBuff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // clean up
            try {
                fis.close();
            } catch (Exception e2) {
            }
            try {
                raf.close();
            } catch (Exception e2) {
            }
        }


    }


}
like image 101
rmalchow Avatar answered Jan 27 '26 09:01

rmalchow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!