WideshoT0
WideshoT0

Reputation: 1

Reverse file java program

I am trying to get a program to work. The input is a source file with lines of text. The output is a target file with the original line of text but in reversed.

ex. 
abcd  -->  dcba
efgh       hgfe

1234       4321

I have looked at a couple of similar questions, but they have gone about this in a different way than I have, and that doesn't exactly solve this individual problem. I have read it through and I think I am just over thinking this. I would greatly appreciate input on why my code is not outputting at all to the target file. I made a stack trace, and it prints all the way through perfectly fine.

Thanks,

code: (command line arguments: source2.txt target2.txt

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

/**
   This program copies one file to another.
*/
public class Reverse
{
   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();
      }

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

Upvotes: 0

Views: 5300

Answers (3)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

I did some modification to your code..

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


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

  File sourceFile=new File("C:/Users/Ruchira/Downloads/in.txt");//input File Path
  File outFile=new File("C:/Users/Ruchira/Downloads/out.txt");//out put file path

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

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

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

This will work

Upvotes: 0

hologram
hologram

Reputation: 529

import java.io.*;
import java.util.*;

class Driver {

public static void main(String[] args) {
    ReverseFile demo = new ReverseFile();
    demo.readFile("source2.txt");
    demo.reverse("target2.txt");
}
}

class ReverseFile {

// Declare a stream of input
DataInputStream inStream;

// Store the bytes of input file in a String
ArrayList<Character> fileArray = new ArrayList<Character>();

// Store file sizes to see how much compression we get
long inFileSize;
long outFileSize;

// Track how many bytes we've read. Useful for large files.
int byteCount;

public void readFile(String fileName) {
             try {
        // Create a new File object, get size
        File inputFile = new File(fileName);
        inFileSize = inputFile.length();

        // The constructor of DataInputStream requires an InputStream
        inStream = new DataInputStream(new FileInputStream(inputFile));
    }

    // Oops.  Errors.
    catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(0);
    }


    // Read the input file
    try {

        // While there are more bytes available to read...
        while (inStream.available() > 0) {

            // Read in a single byte and store it in a character
            char c = (char)inStream.readByte();

            if ((++byteCount)% 1024 == 0)
                System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");

            // Print the characters to see them for debugging purposes
            //System.out.print(c);

            // Add the character to an ArrayList
            fileArray.add(c);
        }

        // clean up
        inStream.close();
        System.out.println("Done!!!\n");
    }

    // Oops.  Errors.
    catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }

    // Print the ArrayList contents for debugging purposes
    //System.out.println(fileArray);
}


public void reverse(String fileName) throws IOException {
        FileWriter output = new FileWriter(fileName);

        for (int i = fileArray.size() - 1; i >= 0; i++) {
            try {
                output.write(fileArray.get(i));
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }

        output.close();
    }
}

That should work. If not, tell me and I'll look into the problem further.

Upvotes: 0

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64056

What output are you seeing??

PrintWriter suppresses IOException and sets an error flag instead; you should use an OutputStreamWriter().

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

Also, don't handle an exception with "something went wrong"; at the very least dump the stack trace so you know what and where it went wrong.

That said, I would probably output each line read to the console, like so:

System.out.println("** Read ["+s+"]");

to confirm I was actually reading the file.

Upvotes: 4

Related Questions