How to implement the PHP function file_get_contents () in JSP (java)?

In PHP, we can use file_get_contents() as follows:

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

How can I implement this in Java (JSP)?

+8
java php jsp
source share
2 answers

Here, the function that I created in Java returned that returns a String of the contents of the file. Hope this helps.

There may be some problems with \ n and \ r, but it should start working 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(); } 
+9
source share

This will read the file from the url and write it to the local file. Just add try / catch and import 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(); 
+7
source share

All Articles