jtcy
asked on
Writing to a file
I need to read in a file, and then create a file which includes the first file content. For example i read file A which contains
abc
def
then i need to read in, and then create a file which has the format:
1: abc
2: def
any idea?
abc
def
then i need to read in, and then create a file which has the format:
1: abc
2: def
any idea?
ASKER
I have this method in class Parser,
public void writeFile(FileReader in) throws java.io.IOException
{
FileWriter writer = new FileWriter("LISTING.txt");
PrintWriter out = new PrintWriter(writer);
BufferedReader inFile = new BufferedReader(in);
String line = inFile.readLine();
int j = 1;
while (line != null)
{
System.out.println(line);
out.println(j+ " :" + line);
j++;
}
inFile.close();
out.close();
}
then in driver class, i do:
parser.writeFile(inFile);
the Listing file did create but is still blank~ :~(
public void writeFile(FileReader in) throws java.io.IOException
{
FileWriter writer = new FileWriter("LISTING.txt");
PrintWriter out = new PrintWriter(writer);
BufferedReader inFile = new BufferedReader(in);
String line = inFile.readLine();
int j = 1;
while (line != null)
{
System.out.println(line);
out.println(j+ " :" + line);
j++;
}
inFile.close();
out.close();
}
then in driver class, i do:
parser.writeFile(inFile);
the Listing file did create but is still blank~ :~(
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I changed it, still doesnt work. 0kb file produced~
ASKER
FileWriter writer = new FileWriter("LISTING.txt");
PrintWriter out = new PrintWriter(writer);
BufferedReader inFile = new BufferedReader(in);
String line = null;
System.out.println(inFile. readLine() ); // I do a test here
and it seems like the file read in is null. how can that be. i am very sure the file is not null. Could it be perhaps we cant pass Filereader object as parameter?
PrintWriter out = new PrintWriter(writer);
BufferedReader inFile = new BufferedReader(in);
String line = null;
System.out.println(inFile.
and it seems like the file read in is null. how can that be. i am very sure the file is not null. Could it be perhaps we cant pass Filereader object as parameter?
SOunds like either the file you are reading is empty, or you have already read all it's contents.
Make sure you haven't already been reading from the FileReader you are passing in.
ASKER
>> Make sure you haven't already been reading from the FileReader you are passing in.
cool. solved it.
cool. solved it.
ASKER
hey, u're my senior LOL
PrintWriter out = new PrintWriter(new FileReader("out.txt"));
String line = null;
int lineno = 1;
while (null!=(line=in.readLine()
{
out.println(lineno+": "+line);
lineno++;
}
in.close();
out.close();