Reputation: 93
I want to read x
bytes at a time from a file, (say "testFile.raw"), and output those bytes to another file.
For example:
read 20 bytes from testFile.raw -> dump into outputfile.jpg
...repeat until done...
Is this possible?
Upvotes: 2
Views: 7390
Reputation: 17534
Here is an example using a byte array of size 20 :
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class FileInputOutputExample {
public static void main(String[] args) throws Exception {
try{
byte[] b = new byte[20];
InputStream is = new FileInputStream("in.txt");
OutputStream os = new FileOutputStream("out.txt");
int readBytes = 0;
while ((readBytes = is.read(b)) != -1) {
os.write(b, 0, readBytes);
}
is.close();
os.close();
}catch(IOException ioe){
System.out.println("Error "+ioe.getMessage());
}
}
}
Upvotes: 4
Reputation: 88
Follow like this give a tumbsup if you like my work
public class ImageTest {
public static void main(String[] args) {
try {
byte[] imageInByte;
BufferedImage originalImage = ImageIO.read(new File(
"c:/imagename.jpg"));
// convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new File(
"c:/imagename.jpg"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}}
Upvotes: -1