This code appends to an already created Excel file:
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
What can we add / modify so that Decrypted.xls should be created if not already created and appended if already created?
You want the FileOutputStream(File file, boolean append) constructor for switching on whether you truncate or append.
According to the Javadocs for the String-accepting constructor of FileOutputStream, rover12, if the file doesn't already exist then it's created. Are you not seeing this behavior?
(And as others have mentioned, be sure to use the constructor that takes the second boolean argument so you can specify that you want to append the file if it already exists...)
Use the constructor:
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls", true);
to append to an existing file, if it doesn't exist. Your example will overwrite the existing one.
Related
This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 7 years ago.
Wanna save some information that I parse from a JSON to a plain text into a file and I also want this information to not be overwritten every time you run the program. It's suppose to work as a simple error logging system.
So far have I tried this:
FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
...
String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());
But when I do this it seems that I overwrite the information all the time and I'm also having problem to save the information I wanna grab from the JSON-array that I've got.
How can I do to make this work?
FileWriter fooWriter = new FileWriter(myFoo, false);
// true to append
// false to overwrite;
where myFoo is the File name
See this link
use append:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));
see this:
How to append text to an existing file in Java
Can you be more elaborate on this? If the problem is just not able to append then you can just add an argument to the FileWriter saying it to append and not write from the beginning.
Check the constructor here:
public FileWriter(String fileName, boolean append) throws IOException
Official Java Documentation:
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
I am new to programming, I need help in understanding the difference between 2 ways of creating a fileinputstream object for reading files. I have seen examples on internet, some have used first one and others second one. I am confused which is better and why?
FileInputStream file = new FileInputStream(new File(path));
FileInputStream file = new FileInputStream(path);
Both are fine. The second one calls the first implicitly.
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
If you have a reference to the file which should be read, use the former. Else, you should probably use the latter (if you only have the path).
Don't use either in 2015. Use Files.newInputStream() instead. In a try-with-resources statement, at that:
final Path path = Paths.get("path/to/file");
try (
final InputStream in = Files.newInputStream(path);
) {
// do stuff with "in"
}
More generally, don't use anything File in new code in 2015 if you can avoid it. JSR 203, aka NIO2, aka java.nio.file, is incomparably better than java.io.File. And it has been there since 2011.
The FileInputStream Class has three constructors. Described in the official documentation:
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
As you see here there is no real difference.
Actually they both have the same way to open a file. The first constructor calls
SecurityManager.checkRead(File.getPath())
And the second one uses the same checkRead() as
SecurityManager.checkRead(name)
if you want use
FileInputStream file = new FileInputStream(new File(path));
for create FileInputStream need more time, if I don't mistake, because this constructor doing some checks with security manager
There is not much difference between the two , as
FileInputStream file = new FileInputStream(path)
implicitly calling other.
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
But to make better use of two available constructors, we can use constructor taking File argument when there is already a File object so we will be avoiding creation of another file object which will be created implicitly If we are using another constructor
Secondly, It is better to create FileinputStream object only after checking the existence of file which can be checked by using file.exists() in that case we can avoid FileNotFoundException.
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();
When I use the following code to create file, it doesn't output a visible file.It doesn't give any exception. In the following code output is exist. That means file is actually there exist. But I can't visible. Actually what is going on here?
File file= new File("/folder/abc.txt");
if(file.exist)
System.out.println("exist");
File file= new File("/folder/abc.txt");
NEVER creates an actual file.
There are two ways to create a file:
Invoke the createNewFile() method on a File object. For example:
File file = new File("foo"); // no file yet
file.createNewFile(); // make a file, "foo" which
// is assigned to 'file'
Create a Writer or a Stream. Specifically, create a FileWriter, a PrintWriter,
or a FileOutputStream. Whenever you create an instance of one of these
classes, you automatically create a file, unless one already exists, for instance
File file = new File("foo"); // no file yet
PrintWriter pw = new PrintWriter(file); // make a PrintWriter object AND
// make a file, "foo" to which
// 'file' is assigned, AND assign
// 'pw' to the PrintWriter
It's a file abstraction class, this doesn't create any file yet. From documentation:
An abstract representation of file and directory pathnames.
You can do lot more than creating a new file, for example checking if such file or directory exist.
Creating a File instance does not create a File on your file system.
You need to call a method of that instance to create the file on the file system
File f = new File("/folder/myfile");
if(!f.exists){
f.createNewFile();
}
As per Java docs,
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
creates only a instance.
Actual file is created by using file.createNewFile();
You are just creating a java object, you need to use:
File file= new File("/folder/abc.txt");
file.createNewFile();
For good practice check if file exists if not then create new one.
File file= new File("/folder/abc.txt");
if(!file.exists())
file.createNewFile();
File file= new File("/folder/abc.txt");
creates java File object, not real file. to create real file call:
file.createNewFile();
or use Stream. For example:
FileOutputStream stream = new FileOutputStream(file);
Just because you create an instance of java.io.File class, that file on the filesystem won't be created instantly.
You have to take steps to actually create it. You will find information easily on this.
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.