Reputation: 23
I am in a situation where i have to cast a java.io.File
object to Struts org.apache.struts.upload.FormFile
object. The type conversion is resulting in error. Can any one suggest a way or a code snippet that i can use to do above operation. Any advice would be helpful.
Upvotes: 1
Views: 7074
Reputation: 30
I implemented the above sugesstion and it worked for me. It dynamically converted a java File to a FormFile. U also have to set the file name & size while converting it dynamically.
public String getFileName() {
return this.file.getName();
}
public int getFileSize() {
return (int) this.file.length();
}
while invoking this wrapper this you have to pass the file location & can directly assign it to the FormFile.
FileWrapper fileWr = new FileWrapper(new File("X://file/file.xlsx"));
FormFile file = fileWr;
String fileName = file.getFileName();
Upvotes: 1
Reputation: 409
You can't directly cast File to FormFile because File does't implement FormFile interface. But you can create wrapper for File object and implement this interface. Something like: import org.apache.struts.upload.FormFile;
import java.io.*;
public class FileWrapper implements FormFile {
private final File file;
public FileWrapper(File file) {
this.file = file;
}
@Override
public String getContentType() {
}
@Override
public void setContentType(String s) {
}
@Override
public int getFileSize() {
}
@Override
public void setFileSize(int i) {
}
@Override
public String getFileName() {
}
@Override
public void setFileName(String s) {
}
@Override
public byte[] getFileData() throws IOException {
byte[] buffer = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(buffer);
fileInputStream.close();
return buffer;
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(file);
}
@Override
public void destroy() {
if (!file.delete()) {
throw new RuntimeException("File " + file.getName() + " can't be deleted");
}
}
}
Here I haven't implemented all methods because implementation depends on your requirements.
Upvotes: 0