aspose file tools*
The moose likes Beginning Java and the fly likes Problem related to java Byte Stream. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem related to java Byte Stream." Watch "Problem related to java Byte Stream." New topic
Author

Problem related to java Byte Stream.

Charanjeet Mamik
Greenhorn

Joined: Sep 06, 2007
Posts: 2
Hi,

I have two query regarding the Byte stream in java.
I was just checking the FileInput strem,where the content of one text file is to be copied to another text file.I used the below Code.
------------------------------------------------------------------------
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimpleCopy
{
public static void main(String [] args) throws IOException
{
FileInputStream in=null;
FileOutputStream out=null;
try
{
in=new FileInputStream("hello.txt");
out=new FileOutputStream ("final.txt");
while( in.read() != -1)
{
System.out.println(in.read());
out.write(in.read());
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}

}
}
-----------------------------------------------------------------
With this code the exact copy is not done.Only few variables are copied.Plus a Batch file is also created.

Now,if i use an integer variable like
------------------------------------
int b;
while((b=in.read()) !=-1);
{
out.write(b);
}
------------------------------------
then the exact copy take place.But here laos the batch file is created.

If anyone can tell why this is happening.

Thanks in advance.
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959


Actually if you see the code above, you call read() few times, in the while loop, in the System.out.println(), and in the out.write(). The first time you call in.read() (in the while loop), you never store the byte that you've read into the out. The same thing when you call System.out.println(), you also never store the byte that you've read into the out. Hence, you're missing few bytes that you've read in the previous two read() calls. That explains why you never get the exact copy.


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Charanjeet Mamik
Greenhorn

Joined: Sep 06, 2007
Posts: 2
Thanks a lot Freddy.i got it now.but one thing more that why the batch file remain there,even though the program execution has been done.means it has been created fine,but it should be deleted when the program execution has been done.but same is not happening.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem related to java Byte Stream.
 
Similar Threads
How to copy and delete files?
Please explain me.
files
unable to downladmultiple file?
Copying Multiple Files Over A Socket