简体   繁体   中英

image not showing when transferred using InputStream and OutputStream in java

This is my test program. I need it to apply somewhere.This may be small, sorry for that. But I'm a starter still. So kindly help me.

try{
        File file1 = new File("c:\\Users\\prasad\\Desktop\\bugatti.jpg");
        File file2 = new File("c:\\Users\\prasad\\Desktop\\hello.jpg");
        file2.createNewFile();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
        String data = null;
        StringBuilder imageBuild = new StringBuilder();
        while((data = reader.readLine())!=null){
            imageBuild.append(data);
        }
        reader.close();
        BufferedWriter writer = new BufferedWriter(new PrintWriter(new FileOutputStream(file2)));
        writer.write(imageBuild.toString());
        writer.close();
    }catch(IOException e){
        e.printStackTrace();
    }

This is file1 在此处输入图片说明

and This is file2 在此处输入图片说明

You can do either of these two:

private static void copyFile(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}

or maybe this if you want to use streams:

private static void copyFile(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
    input = new FileInputStream(source);
    output = new FileOutputStream(dest);
    byte[] buf = new byte[1024];
    int bytesRead;
    while ((bytesRead = input.read(buf)) > 0) {
        output.write(buf, 0, bytesRead);
    }
} finally {
    input.close();
    output.close();
}
}

Images do not contain lines or even characters. You therefore should not be using readLine() or even Readers or Writers. You should rewrite the copy loop using input and output streams directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM