Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement PHP file_get_contents() function in JSP(java)?

Tags:

java

php

jsp

In PHP we can use file_get_contents() like this:

<?php

  $data = file_get_contents('php://input');
  echo file_put_contents("image.jpg", $data);

?>

How can I implement this in Java (JSP)?

like image 234
Koerr Avatar asked Mar 29 '11 10:03

Koerr


2 Answers

Here's a function I created in Java a while back that returns a String of the file contents. Hope it helps.

There might be some issues with \n and \r but it should get you started at least.

// Converts a file to a string
private String fileToString(String filename) throws IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    StringBuilder builder = new StringBuilder();
    String line;    

    // For every line in the file, append it to the string builder
    while((line = reader.readLine()) != null)
    {
        builder.append(line);
    }

    reader.close();
    return builder.toString();
}
like image 196
Ólafur Waage Avatar answered Sep 21 '22 14:09

Ólafur Waage


This will read a file from an URL and write it to a local file. Just add try/catch and imports as needed.

   byte buf[] = new byte[4096];
   URL url = new URL("http://path.to.file");
   BufferedInputStream bis = new BufferedInputStream(url.openStream());
   FileOutputStream fos = new FileOutputStream(target_filename);

   int bytesRead = 0;

   while((bytesRead = bis.read(buf)) != -1) {
       fos.write(buf, 0, bytesRead);
   }

   fos.flush();
   fos.close();
   bis.close();
like image 40
Kaivosukeltaja Avatar answered Sep 22 '22 14:09

Kaivosukeltaja