My java-backed webscript copies file in a repository to a temp folder and edits it for my needs. During its work a new content is generated and it must be written to a created temporary file.
But there is a problem: the first nor the second code below does not updates file's content.
ContentWriter contentWriter = this.contentService.getWriter(tempFile,
ContentModel.PROP_CONTENT, true);
contentWriter.putContent(content);
And the second:
`
WritableByteChannel byteChannel = contentWriter.getWritableChannel();
ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
byteChannel.write(buffer);
byteChannel.close();
`
How to update file's content?
This works for me:
ContentWriter contentWriter = contentService.getWriter(noderef, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype("text/csv");
FileChannel fileChannel = contentWriter.getFileChannel(false);
ByteBuffer bf = ByteBuffer.wrap(logLine.getBytes());
try {
fileChannel.position(contentWriter.getSize());
fileChannel.write(bf);
fileChannel.force(false);
fileChannel.close();
} catch (IOException e){
e.printStackTrace();
}
I'm appending a line to an existing file, so logLine is the appending string.
Related
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 a File that I would like to update based on some user menu selection.
My code gets the IFile
if it does not exist it's been created (with the user's content),and if it exists it should be updated.
My current code is:
String userString= "original String"; //This will be set by the user
byte[] bytes = userString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
try {
if( !file.exists()){
file.create(source, IResource.NONE, null);
}
else{
InputStream content = file.getContents();
//TODO augment content
file.setContents(content, 1, null);
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
IDE.openEditor(page, file);
My problem is that even though I get the original content and set the file's content, I am getting an empty file upon update , i.e., the entire content is being deleted.
What am I doing wrong?
This version of the code in your comment works for me:
InputStream inputStream = file.getContents();
StringWriter writer = new StringWriter();
// Copy to string, use the file's encoding
IOUtils.copy(inputStream, writer, file.getCharset());
// Done with input
inputStream.close();
String theString = writer.toString();
theString = theString + " added";
// Get bytes using the file's encoding
byte[] bytes = theString.getBytes(file.getCharset());
InputStream source = new ByteArrayInputStream(bytes);
file.setContents(source, IResource.FORCE, null);
Note the close of the original input stream and the use of file.getCharset() to use the correct encoding.
I'm trying to delete a PDF file after printing. The PDF is generated using JAVA code and needs to be deleted after the printing process is carried out. However, I am facing an issue while deleting the file. I can't seem to figure out what the problem is.
The error shown while trying to delete the file from its folder is:
"File in Use: The Action can't be completed because the file is open in Java(TM) Platform SE Binary."
The code I've used is as follows:
public String actionPrintReport() {
try {
// Creates a new document object
Document document = new Document(PageSize.LETTER);
File file = new File(fileLocation.concat("\\".concat(fileName)));
FileOutputStream fo = new FileOutputStream(file);
// Creates a pdfWriter object for the FILE
PdfWriter pdfWriter = PdfWriter.getInstance(document, fo);
// Open the document
document.open();
// Add meta data...
// Insert Data...
// Close the document
document.close();
// Create a PDFFile from a File reference
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
PDFFile pdfFile = new PDFFile(bb);
// Create PDF Print Page
PDFPrintPage pages = new PDFPrintPage(pdfFile);
// Create Print Job...
// Close
fo.flush();
fo.close();
fis.close();
if (file.exists()) {
if (file.delete()) {
String check = "yes";
} else {
String check = "no";
}
}
// Send print job to default printer
pjob.print();
actionMsg = "success";
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
}
return ERROR;
}
why not put the deletion in a finally block?
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file.exists()) {
file.delete();
}
}
After discussion with the OP, an approach was investigated to use Apache FileCleaningTracker whereby the File is tracked and then deleted after a Monitored Object has been GC'd.
I have the following situation:
I am able to zip my files with the following method:
public boolean generateZip(){
byte[] application = new byte[100000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// These are the files to include in the ZIP file
String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"};
// Create a buffer for reading the files
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(baos);
// Compress the files
for (int i=0; i<filenames.length; i++) {
byte[] filedata = VirtualFile.fromRelativePath(filenames[i]).content();
ByteArrayInputStream in = new ByteArrayInputStream(filedata);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(application)) > 0) {
out.write(application, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
System.out.println("There was an error generating ZIP.");
e.printStackTrace();
}
downloadzip(baos.toByteArray());
}
This works perfectly and I can download the xy.zip which contains the following directory and file structure:
subdirectory/
----index.html
----webindex.html
My aim is to completely leave out the subdirectory and the zip should only contain the two files. Is there any way to achieve this?
(I am using Java on Google App Engine).
Thanks in advance
If you are sure the files contained in the filenames array are unique if you leave out the directory, change your line for constructing ZipEntrys:
String zipEntryName = new File(filenames[i]).getName();
out.putNextEntry(new ZipEntry(zipEntryName));
This uses java.io.File#getName()
You can use Apache Commons io to list all your files, then read them to an InputStream
Replace the line below
String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"}
with the following
Collection<File> files = FileUtils.listFiles(new File("/subdirectory"), new String[]{"html"}, true);
for (File file : files)
{
FileInputStream fileStream = new FileInputStream(file);
byte[] filedata = IOUtils.toByteArray(fileStream);
//From here you can proceed with your zipping.
}
Let me know if you have issues.
You could use the isDirectory() method on VirtualFile
I am using Eclipse. I want to read number of XML files from a directory. Each XML file contains multiple body tags. I want to extract values of all the body tags. My problem is I have to save each body tag value (text) in a separate .txt file and add these text files in another given directory. Can you plz help how can I create dynamically .txt file and add them in a specified directory?
Thanks in advance.
First specify directory path and name
File dir=new File("Path to base dir");
if(!dir.exists){
dir.mkdir();}
//then generate File name
String fileName="generate required fileName";
File tagFile=new File(dir,fileName+".txt");
if(!tagFile.exists()){
tagFile.createNewFile();
}
add import for java.io.File;
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
replace "myfile.txt" to path to file you needed and file will be created when you say
e.g. "c:\\somedir\\yourfile.txt"
It's not clear why you have mentioned the XML part. But it seems that you are able to get the text from XML file and wanted to write to separate text file.
Please go through this basic tutorial for creating, reading and writing files in Java: http://download.oracle.com/javase/tutorial/essential/io/file.html
Path logfile = ...;
//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();
OutputStream out = null;
try {
out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
...
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Do something like this.
try {
//Specify directory
String directory = //TODO....
//Specify filename
String filename= //TODO....
// Create file
FileWriter fstream = new FileWriter(directory+filename+".txt");
BufferedWriter out = new BufferedWriter(fstream);
//insert your xml content here
out.write("your xml content");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
//Close the output stream
out.close();
}