1

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

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
ThunderDragon
  • 613
  • 3
  • 13
  • 31

3 Answers3

4

The easiest way is to use apache commons FileUtils .

File destFile= new File("somefile.txt");
FileUtils.copyInputStreamToFile(uploadedFile.getInputStream(), destFile);
lzdt
  • 489
  • 1
  • 6
  • 17
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
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