在PHP中,我們可以使用file_get_contents()
這樣的:如何在JSP(java)中實現PHP file_get_contents()函數?
<?php
$data = file_get_contents('php://input');
echo file_put_contents("image.jpg", $data);
?>
我如何在Java中(JSP)實現這一點?
在PHP中,我們可以使用file_get_contents()
這樣的:如何在JSP(java)中實現PHP file_get_contents()函數?
<?php
$data = file_get_contents('php://input');
echo file_put_contents("image.jpg", $data);
?>
我如何在Java中(JSP)實現這一點?
這是我在Java中創建的一個函數,它返回一個文件內容的String。希望能幫助到你。
\ 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();
}
這將從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();
我不能改變'php:// input',這是從閃存,我怎麼能在JSP中獲得'php:// input'? – Koerr 2011-03-29 11:14:55
謝謝,但熱我可以得到'php:// input'? 'fileToString(「php:// input」)'在JSP中返回java.io.FileNotFoundException – Koerr 2011-03-29 11:10:42
如果您需要原始輸入流,那麼您可以使用。 request.getInputStream(); – 2011-03-29 11:13:59
是的,很酷,它的工作,我會在你的答案中加入這個 – Koerr 2011-03-29 11:20:21