I created a file using FileOutputStream and it is an excel file (using HSSF Liberary)
FileOutputStream fileOut = new FileOutputStream(text+".xls");
then I write what I need in my excel file (workbook) and then close the file
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
After closing it I need to display the path of the file to user, (I know that it creates in the folder of my application but I still need to display it to user, maybe via joption/message box)
I tried this :
String absolutePath = fileOut.getAbsolutePath();
JOptionPane.showMessageDialog(null, absolutePath);
but it shows error and it says that it cannot find the method "getAbsolutePath". what should I do ? is there anyway that I can get this path ?
You can change your code to use a file instead as an intermediary.
File myFile = new File(text + ".xls");
FileOutputStream fileOut = new FileOutputStream(myFile);
And then just get the path of that:
String absolutePath = myFile.getAbsolutePath();
Make sure to close the stream when you're done:
fileOut.close();
Ideally though, you shouldn't just create the file wherever the Java path happens to be set. You should probably rethink this and instead ask the user where they want to save the file.
Use new File(text+".xls").getAbsolutePath(). The FileOutputStream doesn't allow accessing the underlying File.
You should get into the habit of reading the javadoc instead of trying random methods. You'll then see what methods exists and what methods don't.
Related
Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());
I've the below project structure in my eclipse.
and my code in servlet is as below.
File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();
here basically I'm trying to write to a file available at /EntityList/entities.txt, but when I run this, I get the exception as below.
SEVERE: Servlet.service() for servlet
[com.luis.servlets.WriteEntityToAFile] in context with path
[/LUISWebUI] threw exception java.io.FileNotFoundException:
\LUISWebUI\EntityList\entities.txt (The system cannot find the path
specified)
I know that I'm going wrong with the path, Can someone please put me in the right direction.
Update
Apologies for the confusion.
I'm sending some data from jsp to servlet to write to the entities.txt file. I'm able to capture it in servlet(Cross checked it by doing sysout).
First of all I think you have a typo problem, try /EntitiesList/entities.txt instead of /EntityList/entities.txt.
Also, move the /EntitiesList/entities.txt under /WEB-INF/ for example, so that your servlet class can access it.
You can read a more detailed explanation in this SO answer.
Edit:
About writing to file: your application will be packaged inside a WAR file so you won't be able to write to it, only read from it (more about this here).
But you can just use this way of creating directly a file outside the WAR and using this location to write your content (before that, make sure you have appropriate rights):
File entityFile = new File(getServletContext().getContextPath() + "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
Or if you want the directory also, you'll have to execute some additional steps, create it first then specify the file name inside it where you want to write:
File entityFolder = new File(getServletContext().getContextPath() + "EntitiesList");
entityFolder.mkdir();
File entityFile = new File(entityFolder, "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
First there is Typo error in your path
Second you should use getResourceAsStream() for loading file for writing.
Code example:
InputStream input = getServletContext().
getResourceAsStream("/WEB-INF/EntityList/entities.txt");
Files.copy(InputStream input , Path target)
//Or Files.copy(Path source, OutputStream out)
It seem easier to use FileInputStream, but it is better to use ResourceStream.
Read here https://stackoverflow.com/a/2161583/8307755
https://stackoverflow.com/a/2308224/8307755
I want to clear the content of a file witch have a specific extension file.tctl, i don't want to change any thing about the file neither deleting it. The file is generated from a specific model checker so that i have just to delete the content and write my own. I tried to print an empty string like that:
PrintWriter writer = new PrintWriter(file.tctl);
writer.print("");
writer.close();
but the file doesn't work any more. So if there's another method to clear the content of the file.
Just remove the print altogether from your code. You've already truncated the file with the new FileOutputStream/PrintWriter/ whatever you use to open it. No I/O or truncate() necessary. Don't use append mode.
Most easy way I guess
new RandomAccessFile("filename.ext", "rw").setLength(0);
Call your write() method like this:
.write((new String()).getBytes());
This will make your file empty. If that doesn't works, try with this:
FileOutputStream erasor = new FileOutputStream("filename.ext");
erasor.write((new String()).toByteArray());
erasor.close();
Or just try to overwrite the file
//open file in override mode
FileOutputStream out = new FileOutputStream("filename.ext");
//now anything that we write here will remove the old one so just write space ("") here
You have to use a FileOutputStream and then you have the truncate() method:
File f = new File("path-of-the-file.here");
FileChannel channel = new FileOutputStream(f, true).getChannel();
channel.truncate(0);
channel.close();
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes()
fos.close();
Above is how i write my files. Now is there a limit to it? i'm asking this because i set some text to it that i get from my text view, then later, when i get the text from that file, it isn't the full text.Secondly, how would i delete a file when using the above method?
Well for the limitations of writing in file is depends on the Available Free Memory.
for deleting a file simply use delete method as below,
File fos = new File(FILENAME);
fos.delete();
You want Context.deleteFile(String filename) to delete the file. There shouldn't be any reason why the file is limited. Check your writing and reading code.
I'm reading a bunch of files from an FTP. Then I need to unzip those files and write them to a fileshare.
I don't want to write the files first and then read them back and unzip them. I want to do it all in one go. Is that possible?
This is my code
FTPClient fileclient = new FTPClient();
..
ByteArrayOutputStream out = new ByteArrayOutputStream();
fileclient.retrieveFile(filename, out);
??????? //How do I get my out-stream into a File-object?
File file = new File(?);
ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
Any ideas?
You should use a ZipInputStream wrapped around the InputStream returned from FTPClient's retrieveFileStream(String remote).
You don't need to create the File object.
If you want to save the file you should pipe the stream directly into a ZipOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// do whatever with your zip file
If, instead, you want to open the just retrieved file work with the ZipInputStream:
new ZipInputStream(fileClient.retrieveFileStream(String remote));
Just read the doc here and here
I think you want:
ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
Then read your data from the ZipInputStream.
As others have pointed out, for what you are trying to do, you don't need to write the downloaded ZIP "file" to the file system at all.
Having said that, I'd like to point out a misconception in your question, that is also reflected in some of the answers.
In Java, a File object does no really represent a file at all. Rather, it represents a file name or *path". While this name or path often corresponds to an actual file, this doesn't need to be the case.
This may sound a bit like hair-splitting, but consider this scenario:
File dir = new File("/tmp/foo");
boolean isDirectory = dir.isDirectory();
if (isDirectory) {
// spend a long time computing some result
...
// create an output file in 'dir' containing the result
}
Now if instances of the File class represented objects in the file system, then you'd expect the code that creates the output file to succeed (modulo permissions). But in fact, the create could fail because, something deleted the "/tmp/foo", or replaced it with a regular file.
It must be said that some of the methods on the File class do seem to assume that the File object does correspond to a real filesystem entity. Examples are the methods for getting a file's size or timestamps, or for listing the names in a directory. However, in each case, the method is specified to throw an exception if the actual file does not exist or has the wrong type for the operation requested.
Well, you could just create a FileOutputStream and then write the data from that:
FileOutputStream fos = new FileOutputStream(filename);
try {
out.writeTo(fos);
} finally {
fos.close();
}
Then just create the File object:
File file = new File(filename);
You need to understand that a File object doesn't represent any real data on disk - it's just a filename, effectively. The file doesn't even have to exist. If you want to actually write data, that's what FileOutputStream is for.
EDIT: I've just spotted that you didn't want to write the data out first - but that's what you've got to do, if you're going to pass the file to something that expects a genuine file with data in.
If you don't want to do that, you'll have to use a different API which doesn't expect a file to exist... as per Qwerky's answer.
Just change the ByteArrayOutputStream to a FileOutputStream.