I have an application which saves .docx files to a FTP server. To store the file on the FTP server the FTP client needs the InputStream of the file, but here comes the problems. I use docx4j to save the text I want to a temp file on the file system, after that I get the InputStream of that file and stores it on the FTP server. But when I try to open it says that it is corrupted. Here is my sample code:
public void setText(String text) throws BusinessException {
//My utility class, used for ftp processes(such as storing, deleting files
FtpProcesses ftp = new FtpProcesses(Consts.ADMIN_FTP_USERNAME, UserType.ADMIN);
String filePath = ftp.getFileFolderRelativePath(FileType.ARTICLE, String.valueOf(this.getVersionsCount()), String.valueOf(this.getId()));
File outputFile;
InputStream stream;
Text fileText;
R run;
P paragraph;
ObjectFactory factory = Context.getWmlObjectFactory();
try {
outputFile = File.createTempFile("tempFile", ".docx");
paragraph = factory.createP();
run = factory.createR();
fileText = factory.createText();
fileText.setValue(text);
run.getContent().add(fileText);
paragraph.getContent().add(run);
WordprocessingMLPackage word = WordprocessingMLPackage.createPackage();
word.getMainDocumentPart().addObject(paragraph);
word.save(outputFile);
stream = new FileInputStream(outputFile);
ftp.uploadFile(filePath, stream);
} catch (IOException | Docx4JException e) {
e.printStackTrace();
throw new BusinessException(Errors.FILE_UPLOAD_ERROR);
}
}
So as you can see I getting the InputStream directly after saving the file. Is there some other way for getting it with docx4j so that it can be saved properly on the ftp?
Related
I have created a AWS lambda function that takes some files from an S3 bucket, zips them and transfers the zipped file to a sftp server. When I look in the server, I see that the tmp folder has been carries over with the files and a tmp folder gets created inside the zip file. When I open the zip file, there is a tmp folder and inside that folder are the files that I had zipped. I have scoured the internet and AWS trying to figure out how to change the directory in AWS Lambda when I am retrieving the files to be zipped, but have not had any luck. I don't want to have a tmp folder in my zip file. When I unzip the zip file, I just want to see the files that I had selected to be zipped without any folders. Does anyone know how to do this? I am programming in Java.
My code is below.
private DownloadFile(){
File localFile = new File(fileName);
//pull data and audit files from s3 bucket
s3Client.getObject(new GetObjectRequest("pie-dd-demo/daniel20", fileName), localFile);
zipOS = new ZipOutputStream(fos);
//send files to be zipped
writeToZipFile(fileName, zipOS);
}
public static void writeToZipFile(String path, ZipOutputStream zipStream)
throws FileNotFoundException, IOException {
File aFile = new File(path);
FileInputStream fis = new FileInputStream(aFile);
ZipEntry zipEntry = new ZipEntry(path);
try {
zipStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipStream.write(bytes, 0, length);
System.out.println(path + "write to zipfile complete");
}
} catch (FileNotFoundException exception) {
// Output expected FileNotFoundExceptions.
} catch (Exception exception) {
// Output unexpected Exceptions.
}
zipStream.closeEntry();
fis.close();
}
I think the problem is that you are creating a zip entry using new ZipEntry(path) and that means that the resulting zip file will contain the full path as the name of the zip entry.
You can retrieve the actual filename from a full path/file in Java as follows:
File f = new File("/tmp/folder/cat.png");
String fname = f.getName();
You can then use fname to create the zip entry by calling new ZipEntry(fname).
I have a working code (at least in eclipse), in which I work with some files: I have a .dot file I write into some text, so I can read it to create a graph. Then I save the graph into a .png image, which I display on a frame..
My problem is: In the executable .jar file I can´t acces these files, and also - if i know it right - I can´t even change em runtime. So I tried to work with Streams. I can access the .dot file like:
$InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");$
But I have no clue how can i write into it. I found OutputStreamWriter, but it also requires a path, which I can´t acces like I accessed the InputStream..I also struggle with reading the text from the file and creating the .png file... Can you please help me? Is it even possible to work with these files at runtime?
I had the same problem accessing the background image of the frame, but I found a solution:
$URL bgPath = this.getClass().getResource("/background.jpg");
panel = new JLabel(new ImageIcon(bgPath));$
So I really hope there exists some similar solution for the files I work with..
private void createGraph() throws IOException {
/* Creating the graph into "graf.dot" file.
* The format is in DOT language.
*/
String fileName = "src/main/resources/graf.dot";
InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
/* Here I write the content into *graph_string**/
br.close();
try {
FileOutputStream outputStream = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//FileWriter writer = new FileWriter(fileName);
writer.write(graph_string);
writer.close();
}catch (IOException e) {
System.out.println("Error writing into file");
}finally {
drawGraph();
}
}
private void drawGraph() throws IOException {
/*
* Reading the graph from file for visualization
*/
String fileName = "src/main/resources/graf.dot";
InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
File file = new File("src/main/resources/graf.dot");
String str="";
try {
str = FileUtils.readFileToString(file, "UTF-8");
} catch (IOException e) {
System.out.println("Errorrr reading from file.");
}
MutableGraph g = Parser.read(str);
Graphviz.fromGraph(g).render(
Format.PNG).toFile(new File("src/main/resources/graph.png"));
BufferedImage background = ImageIO.read(new File("src/main/resources/graph.png"));
panel = new JLabel(new ImageIcon(background));
...
}
My Code is:
String MyFile = "Riseone.dat";
String MyContent = "This is My file im writing\r\n";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS),MyFile);
outputStream = new FileOutputStream(file);
outputStream.write(MyContent.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
When I try this code MyFile creates in data/data/appfolder/files/Riseone.dat
but I want to create a file in DIRECTORY_DOWNLOADS.
also I want the file to write in append for next write action.
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), MyFile); corresponds to the file inside the Downloads directory of external shared storage. You might have seen older file in internal storage. Check it carefully.
If you want to append the data for next write, use append mode to create FileOutputStream using another constructor public FileOutputStream(File file, boolean append)
outputStream = new FileOutputStream(file, true);
I have excel file with two Ms Word file embedded in it.
I am using Apache POI to read Embedded object from excel file in java.
Problem is when I read embedded file and save it on Disk and opened saved file in Ms Word, MS Word couldn't read its format.
If opened from excel file directly it opened and Ms Word read it properly.
Anyone help me.
[Code]
public class test {
public static void main(String[] args) throws Exception {
File file = new File("C:/Book2.xls");
NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
for (HSSFObjectData obj : wb.getAllEmbeddedObjects()) {
String oleName = obj.getOLE2ClassName();
DirectoryNode dn = (DirectoryNode)obj.getDirectory();
Iterator<Entry> ab = dn.getEntries();
if(oleName.contains("Document")){
HWPFDocument embeddedWordDocument = new HWPFDocument(dn);
String docTitle = embeddedWordDocument.getSummaryInformation().getTitle();
InputStream is ;
Entry entry = ab.next();
is = dn.createDocumentInputStream(entry);
FileOutputStream fos = new FileOutputStream("d:/"+docTitle+".doc");
System.out.println(is.available());
System.out.println(((DocumentEntry)entry).getSize());
IOUtils.copy(is, fos);
fos.close();
is.close();
}
}
fs.close();
}
}
i have a stupid question here i'm implementing upload button with vaadin and i want the users to upload only compressed files (.zip,.rar..), imake a search but i didn't find something useful :
so i tried to do this , i know it's not good solution because the user already uploaded the selected file :
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
String fileName ;
String userHome = System.getProperty( "user.home" );
try {
// Open the file for writing.
file = new File(userHome+"/kopiMap/runtime/uploads/report/" + filename);
fileName= file.getName();
//Here i will get file extension
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
Notification.show(
"Could not open file<br/>", e.getMessage(),
Notification.TYPE_ERROR_MESSAGE);
return null;
}
return fos; // Return the output stream to write to
}
So how to do it before uploading
you can check the mimeType and if it is application/zip
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
if(mimeType.equals("application/zip"))
//Here you can restrict
You can add this and it will work (all done by HTML 5 and most browser support now accept attribute) - this is example for .csv files:
upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");