1

I am beginner to spring,

i am trying to download a file from net and store it in my local disk but i am getting compilation error as mentioned in tile

i tried to make ResponseEntity and json as String it worked but says image is damaged or not supported when i try to open image

my code:

public static void main(String arg[]) throws IOException
    {




        HttpHeaders requestHeaders = new HttpHeaders();
        //requestHeaders.setAcceptEncoding(ContentCodingType.IDENTITY);
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Add the String message converter
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

        // Make the HTTP GET request, marshaling the response to a String
        ResponseEntity<byte[]> response = restTemplate.exchange("http://www.nndb.com/people/954/000354889/duke-kahanamoku-2-sized.jpg", HttpMethod.GET, requestEntity,byte[].class);
        File file = new File("/Users/crohitk/Desktop/image.jpg");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        byte[] json =response.getBody();
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(json);
        bw.close();

        System.out.println("Done");     


        System.out.println(response.getBody());
        }
Labeo
  • 5,831
  • 13
  • 47
  • 77
  • You can simplify and use `Files.write()`, see http://www.leveluplunch.com/java/tutorials/038-retrieve-file-spring-resttemplate/ –  Aug 25 '15 at 04:41
  • 2
    If you look at the documentation of `BufferedWriter`, you will see that there is no method that takes a `byte[]`. See http://stackoverflow.com/questions/1769776/how-can-i-write-a-byte-array-to-a-file-in-java. – ajb Aug 25 '15 at 04:42

1 Answers1

2

Writer is used to write characters. Use a OutputStream to write bytes into your file.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • @Labeo To find the difference between IO Strems and Writers/Reader classes go through this discussion: http://stackoverflow.com/questions/2822005/java-difference-between-printstream-and-printwriter – Tarun Gupta Aug 25 '15 at 04:53