Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem related to java Byte Stream.

 
Charanjeet Mamik
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Charanjeet Mamik
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic