PDA

View Full Version : Java problem



vik_2010
February 12th, 2010, 05:29 AM
Sorry for bringing up an old thread. But if anyone could help me with this, I'd appreciate it.

I'm trying to write a simple java program that uses I/O streams, taking input from one file and outputting it into another. I'm taking input from the windowspager.ini file (courtesy Jochen Baier, creator of the program) and outputting it to a file on my desktop.



import java.io.*;
public class firstClass {
public static void main(String[] args) throws IOException {
System.out.println("Hello world");
System.out.println("We are going to create a txt file");
BufferedReader bi = new BufferedReader(new FileReader("C:\\Users\\Vikram\\Desktop\\windowspager-0.90\\windowspager-0.90\\windowspager64bit\\Windowspager.ini"));
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\Vikram\\Desktop\\out.txt"));

while (bi.readLine() != null) {
String line = bi.readLine();
out.write(line);
out.write("\r\n");
System.out.println("Writing...");

}
System.out.println("Done");
bi.close();
out.close();
}
}
The problem is that the file created only has every OTHER line in the original. I'm not sure if it has something to do with the carriage return+line feed combo, since I'm not used to it as I usually work on Ubu.

If anyone could just point out what's going on, I would appreciate it.

cariboo
February 12th, 2010, 06:33 AM
A new thread is better than tacking your post on to an old thread.

LKjell
February 12th, 2010, 06:37 AM
For input check Scanner class. Output you can check out PrintWriter.


PrintWriter file = null;
String lines[] = ...
try {
file = new PrintWriter(new FileWriter(filename));
for(String line : lines) {
file.println(line);
}

} catch (Exception e) {
System.out.println("Got some error when trying to write to file");
} finally {
if (file != null) {
file.close();
System.out.println("Finish writing to file");
}
}

stumbleUpon
February 12th, 2010, 06:57 AM
The problem is here


while (bi.readLine() != null) {
String line = bi.readLine();
out.write(line);
out.write("\r\n");
System.out.println("Writing...");

}


You have already read in the first line when you do bi.readLine() to check if u have reached the end of the file. You then again read in another line and write it out. Obviously you will only read every other line. The code segment below works.



String line = bi.readLine();
while (line != null) {
out.write(line);
out.write("\r\n");
System.out.println("Writing...");
line = bi.readLine();
}

vik_2010
February 12th, 2010, 08:34 AM
Thanks for the help, stumble.

LKJell brought up a point that has been at the back of my mind for a while:

what's the difference between the functionalities offered by the Scanner and FileWriter classes?

The only difference seems to me to be that the scanner class offers the ability to parse input based upon a specific character.

-V