How do I convert an uploaded file from apache's UploadedFile
class to a java.io.File
class?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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");
回答2:
The easiest way is to use apache commons FileUtils .
File destFile= new File("somefile.txt");
FileUtils.copyInputStreamToFile(uploadedFile.getInputStream(), destFile);
回答3:
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.