Reputation: 51
I am doing an assignment for class that has us read and write to a file, that has even and odd numbers from one to one hundred. The file must read and write both instances of odd and even numbers. I got the file to output both even and odd numbers, but my problem is getting each to show up on separate lines in the console. Everything prints to one line. Sorry if this may be a repeat post, but I have tried newline()
, "\n"
, and "\r\n"
nothing is working. Anyone knows of an example of how I can accomplish this? I'm using Windows.
Here's my code:
package textFile_I_O;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class TextFile_I_O
{
public static void main(String[] args) throws IOException//throws IOException
{
evenFile();
oddFile();
FileInputStream file = new FileInputStream("numbers.dat");
DataInputStream data = new DataInputStream(file);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data));
System.out.println(buffer.readLine());
buffer.close();
}
private static void evenFile() throws IOException
{
BufferedWriter write1 = new BufferedWriter(new FileWriter("numbers.dat"));
for(int i = 1; i <= 100; i++)
if(i % 2 == 0)
{
write1.write(i + ",");
}
write1.close();
}
private static void oddFile() throws IOException
{
PrintWriter write2 = new PrintWriter(new FileWriter("numbers.dat", true));
for(int j = 1; j <= 100; j++)
if(j % 2 == 1)
{
write2.print(j + ",");
}
write2.close();
}
}
Upvotes: 0
Views: 105
Reputation: 878
While calling the second method i.e oddFile()
try to put a new line character \n
before writing into the file. This will enter all the odd numbers into a new line.
write2.write("\n");
While retrieving the data from file use a while loop with a condition as
String s=null;
while((s=buffer.readLine())!=null)
{
System.out.println(s);
}
Upvotes: 1
Reputation: 1219
You try this way..
private static void oddFile() throws IOException
{
PrintWriter write2 = new PrintWriter(new FileWriter("numbers.dat", true));
write2.print("\n");
for(int j = 1; j <= 100; j++)
if(j % 2 == 1)
{
write2.print(j + ",");
}
write2.close();
}
In your main Method :: Print as below
evenFile();
oddFile();
FileInputStream file = new FileInputStream("numbers.dat");
DataInputStream data = new DataInputStream(file);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data));
String line = "";
while((line=buffer.readLine())!=null)
{
System.out.println(line);
}
buffer.close();
It should solve your problem. I guess
Upvotes: 1