I am writing a program to copy large files, so I want to read specific number of bytes and write to another file. I want to copy the file and get same number of bytes. But I am getting more. Plus I also want the contents of the file to remain same. What am I doing wrong here? If someone can explain why am I getting this extra text, that would be great.
test.txt
sometext sometext sometext sometext
sometext sometext sometext sometext
sometext sometext sometext sometext
sometext sometext sometext sometext
Practice.java
public class Practice{
public static void main(String[] args){
byte[] buffer = new byte[100];
try{
FileInputStream f = new FileInputStream("test.txt");
FileWriter writer = new FileWriter("copy_test.txt");
int b;
while ((b=f.read(buffer)) != -1 )
writer.write(new String(buffer));
writer.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
copy_test.txt
sometext sometext sometext sometext
sometext sometext sometext sometext
sometext sometext sometext sometext
sometext sometext sometext sometext
metext sometext sometext
sometext sometext sometext
There are several problems with your code:
new String(byte[])
instead of specifying an encodingFileWriter
)String
constructor overloads taking an offset and number of bytes, and passing 0
and b
for arguments, although I wouldn't. Use a try-with-resources statement.Exception
- that's usually a bad idea. Catch specific exceptions if you must; personally I have very few catch
blocks - generally if something goes wrong, it's appropriate for that to abort the whole of the current operation. (There are cases where you can retry etc, of course.) I understand this may just be in your sample code here, and not in your real code.Files.copy
to avoid having to write any code at all, assuming you're using Java 7. (And if you're not, you should be!)If you just want to copy an InputStream
to an OutputStream
(and you haven't got a utility library available - this is part of a lot of libraries) you can just use something like:
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
See more on this question at Stackoverflow