How to get java.io.File from Apache's Uploaded

2019-08-01 03:12发布

How do I convert an uploaded file from apache's UploadedFile class to a java.io.File class?

3条回答
干净又极端
2楼-- · 2019-08-01 03:22
InputStreamReader reader = new InputStreamReader(uploadedFile.getInputstream());
BufferedReader br = new BufferedReader(reader);
File f = new File("file.txt");
FileWriter fw = new FileWriter(f,false);
BufferedWriter bw = new BufferedWriter(fw);

while((line = br.readLine()) != null){
   fw.write(line + System.lineSeparator());
}

This code will return your uploaded file in txt file.

查看更多
再贱就再见
3楼-- · 2019-08-01 03:23

The easiest way is to use apache commons FileUtils .

File destFile= new File("somefile.txt");
FileUtils.copyInputStreamToFile(uploadedFile.getInputStream(), destFile);
查看更多
做个烂人
4楼-- · 2019-08-01 03:29

Looking at the documentation (UploadedFile and File) for both classes, here's one solution.

Since you can access the InputStream of the UploadedFile, you can read in the data of the uploaded file and write it to a temporary location or another location that your application can manage.

// assume that you have the UploadedFile object named uploadedFile
InputStreamReader reader = new InputStreamReader(uploadedFile.getInputStream());
int partition = 1024;
int length = 0;
int position = 0;
char[] buffer = new char[partition];
FileWriter fstream = new FileWriter("out.tmp");
do{
    length = reader.read(buffer, position, partition)
    fstream.write(buffer, position, length);
}while(length > 0);
File file = new File("out.tmp");
查看更多
登录 后发表回答