0

This code is trying to read a file then reverse it to an output file. When it writes it (without reversing) the output is the same. But when it is reversed the output is written ALL on ONE line in the output file.

  int i;
    int x = 0;
    int[] ar = new int[9999];
    BufferedInputStream fin;
    BufferedOutputStream fout;
    try {

        File f1 = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt");
        File f2 = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt");
        fin = new BufferedInputStream(new FileInputStream(f1));
        fout = new BufferedOutputStream(new FileOutputStream(f2));


        while ((i = fin.read()) != -1) { //reads file into an array
            ar[x] = i;
            x++;
        }

        for(int y = (x-1); y >= 0; y--){ 
        //writes to a file from the end of the array
            fout.write(ar[y]);
        }

        System.out.println();
        fin.close();
        fout.close();
        } catch (FileNotFoundException e) {
        System.out.println("File is NOT found.");
    }

I'm using BufferedInputStream and BufferedOutputStream

  • 2
    For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Nov 04 '12 at 03:45
  • 1
    It might be a `\r\n` vs `\n` issue. If you're running windows try opening it with a reader that supports both (such as Notepad++). If my guess is correct then it will say Unix in the corner in the output file. But I post this as a comment not an answer because you haven't given us enough information to know for sure. – durron597 Nov 04 '12 at 03:49
  • Sorry, misread your post. You might try comparing the size of the actual file with what was read in to make sure you're reading them in the first place. – Ender Nov 04 '12 at 03:55
  • @durron597 I'm using Notepad but not Notepad++ – InspiringProgramming Nov 04 '12 at 04:12
  • @Ender The problem is with the reversion because when I printed out the file without reversion, it was an exact copy of it. – InspiringProgramming Nov 04 '12 at 04:13
  • @AndrewThompson I updated the code for a better illustration. Thnx. – InspiringProgramming Nov 04 '12 at 04:46
  • 1
    @InspiringProgramming: That's the problem, regular Notepad won't display \n correctly. Download Notepad++, you'll be happy you have it not just for this but for everything – durron597 Nov 04 '12 at 04:47

1 Answers1

2

Probably you are reading \r\n and writing back \n\r.

You have to handle \r\n as a separate entity.

thedayofcondor
  • 3,860
  • 1
  • 19
  • 28