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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5471406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:16:10  来源:igfitidea点击:

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

javaphpjsp

提问by Koerr

In PHP we can use file_get_contents()like this:

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

<?php

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

?>

How can I implement this in Java (JSP)?

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

回答by ólafur Waage

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

这是我不久前在 Java 中创建的一个函数,它返回文件内容的字符串。希望能帮助到你。

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

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

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

回答by Kaivosukeltaja

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

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

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