Search code examples
javafileinputstreamfileoutputstream

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 enter image description here

and This is file2 enter image description here


Solution

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