开发者

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

开发者 https://www.devze.com 2023-02-20 07:16 出处:网络
In PHP we can use file_get_contents() like this: <?php $data = file_get_contents(\'php://input\'); echo file_put_contents(\"image.jpg\", $data);

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)?


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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消