从java中的文件一次读取x个字节

时间:2016-02-07 09:24:16

标签: java io bufferedinputstream

我想一次从文件中读取x个字节,(比如" testFile.raw"),并将这些字节输出到另一个文件。

例如:

read 20 bytes from testFile.raw -> dump into outputfile.jpg
...repeat until done...

这可能吗?

2 个答案:

答案 0 :(得分:3)

以下是使用大小为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());
            }
         }
     }

答案 1 :(得分:-1)

如果你喜欢我的作品,请按照这样的方式给出一个tumbsup

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());
    }
}}