How do I convert an uploaded file from apache's UploadedFile
class to a java.io.File
class?
Asked
Active
Viewed 1.1k times
1

Bhesh Gurung
- 50,430
- 22
- 93
- 142

ThunderDragon
- 613
- 3
- 13
- 31
3 Answers
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");

mauris
- 42,982
- 15
- 99
- 131
-
error shown in the following line- **while(length = reader.read(buffer, position, partition))** Type mismatch: cannot convert from int to boolean – ThunderDragon Dec 12 '11 at 05:21
-
Tried this method but copied file was broken. System said "cannot open file". – Bahadir Tasdemir Nov 19 '15 at 06:51
0
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.

kadir4102
- 1
- 4