Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes I/O and Streams and the fly likes BufferedWriter Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "BufferedWriter Problem" Watch "BufferedWriter Problem" New topic

BufferedWriter Problem

Karthik Krishnamurthy
Ranch Hand

Joined: Feb 04, 2005
Posts: 118
I need to copy a file into a different file after cutting off the last few lines based on a check.
The problem I am encountering is that the final file is shorter than the original and cutting off portions that should be there.
The original file is of length 779KB and the new file is only 768KB.
Here is the code.
any help will be appreciated.

BufferedReader bufIn = new BufferedReader(new FileReader(currFile)) ;
File outFile = new File("out.txt");
if(!outFile.exists()) {
BufferedWriter bufOut = new BufferedWriter(new FileWriter(outFile)) ;

String lineByLine = bufIn.readLine();
while (lineByLine!=null){

lineByLine = bufIn.readLine();
if (lineByLine.startsWith("T837")){
}//end if
}//end while
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Well, two things. First of all, using "write" to put a newline into a file will put only one newline (ASCII 10) character into the file; it won't put the platform-appropriate line-ending characters into the file. If you're on UNIX, there's no problem. If it's a Windows file you're reading, then you'll lose one character for each line, because Windows text files use two characters (0x0a, 0x0d) at the end of each line. Either use the line.separator system property, or use a PrintWriter wrapped around the BufferedWriter (or instead of it) and use "println()" which will do the right thing automatically.

The second issue is that you don't close the file in the code here; until you call close() on the BufferedWriter, the file may not contain everything you've written to it. The balance of the text is still in the BW's buffer.

Finally, this isn't advanced Java. I'm going to move this thread to our I/O forum.

[Jess in Action][AskingGoodQuestions]
Karthik Krishnamurthy
Ranch Hand

Joined: Feb 04, 2005
Posts: 118
That worked.
Sorry for the cross posting.

I agree. Here's the link:
subject: BufferedWriter Problem
It's not a secret anymore!