如何在JSP(java)中实现PHP file_get_contents()函数?

Koe*_*err 8 php java jsp

在PHP中我们可以file_get_contents()像这样使用:

<?php

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

?>
Run Code Online (Sandbox Code Playgroud)

如何在Java(JSP)中实现它?

Óla*_*age 9

这是我在Java中创建的一个函数,它返回一个文件内容的String.希望能帮助到你.

\n和\ r \n可能存在一些问题,但它应该至少让你开始.

// 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您需要原始输入流,那么您可以使用.request.getInputStream(); (2认同)

Kai*_*aja 7

这将从URL读取文件并将其写入本地文件.只需根据需要添加try/catch和import.

   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();
Run Code Online (Sandbox Code Playgroud)