Rose Rose - 1 year ago 83
Java Question

Read from file and manipulate then write in another file using java?

I have data file “ReadFile1.txt”. I want to read each data from ReadFile1.txt and manipulate those data then write the results in another file “WriteFile2.txt”. Here is my function. The problem is it only reads 2nd,4th, and so on and does write only 2nd result. What’s wrong in this code? I appreciate your help.

public void doManipulate() throws NumberFormatException, IOException {
int multiple = 10;

try {
FileInputStream file = new FileInputStream("ReadFile1.txt");
InputStreamReader input = new InputStreamReader(file);
BufferedReader reader = new BufferedReader(input);

String data1;
while ((data1 = reader.readLine()) != null) {

int data2 = 0;
data1 = reader.readLine();

data2 = Integer.parseInt(data1);
int compressedFrames = data2*multiple;

File file2 = new File("WriteFile2.txt");
FileWriter writer = new FileWriter(file2);

writer.write(String.valueOf(compressedFrames) + "\n");




} catch (IOException e) {


Answer Source

You're calling reader.readLine() twice for every iteration of the while loop - the first time is in the loop declaration, which reads ever odd line, and the second is just a couple of lines down (data1 = reader.readLine();). The second call is blowing away anything read by the first before you have a chance to parse it. Removing the second call should fix the "every other line" issue.

Another issue is that you're closing the writer at every iteration of the while loop - don't close the writer until the while loop is done or your output file will only have the first parsed data element in it after your program closes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download