This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "BufferedWriter Problem" Watch "BufferedWriter Problem" New topic
Author

BufferedWriter Problem

Karthik Krishnamurthy
Ranch Hand

Joined: Feb 04, 2005
Posts: 118
Hi,
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()) {
outFile.createNewFile();
}
BufferedWriter bufOut = new BufferedWriter(new FileWriter(outFile)) ;

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

lineByLine = bufIn.readLine();
bufOut.write(lineByLine+"\n");
if (lineByLine.startsWith("T837")){
break;
}//end if
}//end while
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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
Thanks
That worked.
Sorry for the cross posting.

Karthik
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: BufferedWriter Problem
 
Similar Threads
tricky question
scope problem
comparing the file before i append it to the other
append method
Replacing text in a stream