2011-03-29 758 views

回答

9

这是我在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(); 
} 
+0

谢谢,但热我可以得到'php:// input'? 'fileToString(“php:// input”)'在JSP中返回java.io.FileNotFoundException – Koerr 2011-03-29 11:10:42

+2

如果您需要原始输入流,那么您可以使用。 request.getInputStream(); – 2011-03-29 11:13:59

+0

是的,很酷,它的工作,我会在你的答案中加入这个 – Koerr 2011-03-29 11:20:21

7

这将从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(); 
+0

我不能改变'php:// input',这是从闪存,我怎么能在JSP中获得'php:// input'? – Koerr 2011-03-29 11:14:55