Link to home
Start Free TrialLog in
Avatar of jtcy
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?
Avatar of Mick Barry
Mick Barry
Flag of Australia image

BufferedReader in = new BufferedReader(new FileReader("in.txt"));
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();

Avatar of jtcy
jtcy

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~ :~(
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jtcy

ASKER

I changed it, still doesnt work. 0kb file produced~
Avatar of jtcy

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?
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.
Avatar of jtcy

ASKER

>> Make sure you haven't already been reading from the FileReader you are passing in.


cool. solved it.
Avatar of jtcy

ASKER

hey, u're my senior LOL