How do I write an object to a file that already exists? - java

I'm having a problem with an assignment from school. I'm meant to output an arraylist of objects to a file, which I can do. But I'm supposed to check if the file exists, and if it does, then to output to that file, and not create a new one.
I've tried putting the FileOutputStream declaration outside of my if statement, but then the file will always exist.
I've also tried creating a new ObjectOutputStream in my first half of the if statement, but I get an IOException about the headers.
How do I write the objects (of class Employee) to a file that already exists?
public void saveEmployeesToFile() {
try {
File employeeFile = new File("CurrentEmployees.emp");
if (employeeFile.exists()) {
System.out.println("File already exists");
} else {
FileOutputStream employeeFileObject = new FileOutputStream(employeeFile);
ObjectOutputStream output = new ObjectOutputStream(employeeFileObject);
for (Employee thisEmp : getEmployees()) {
output.writeObject(thisEmp);
}
System.out.println("Employees successfully saved to new file");
employeeFileObject.close();
output.close();
}
} catch (IOException ioe) {
System.out.println("Error initializing stream");
System.out.println(ioe.getMessage());
}
}

You can leverage the newer NIO package.
Your question is essentially, "how do I create a FileOuputStream for a file that already exists?"
Path employeeFilePath = Paths.get(employeeFile.toURI());
FileOutputStream employeeFileObject;
if (employeeFile.exists()) {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.TRUNCATE_EXISTING);
}
else {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.CREATE_NEW);
}
// Proceed to write data

Related

How to read / write in a file embedded in a jar [duplicate]

So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?
You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.
Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest
Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}

Java, how to write or add instead of overwriting a textfile?

I wonder why my program overwrites existing text in the textfile instead of adding a new line of text?
public class WriteToFile {
public void registerTrainingSession(Customer customer) {
Path outFilePath = Paths.get("C:\\Users\\Allan\\Documents\\Nackademin\\OOP\\Inlämningsuppgift2\\visits.txt");
try (BufferedWriter save = Files.newBufferedWriter(outFilePath)) {
String trainingSession = String.format("Member: %s %s\nPersonalnumber: %s\nTraining session date: %s\n", customer.getFirstName(),
customer.getLastName(), customer.getPersonalNumber(), LocalDate.now());
save.write(trainingSession);
save.flush();
}
catch (NullPointerException e) {
JOptionPane.showMessageDialog(null, "Customer info is missing!");
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "File could not be created.");
}
}
}
The code overwrites the file because you didn't specify an OpenOption on the newBufferedWriter() call.
As the javadoc says:
If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
Try:
Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
StandardOpenOption.WRITE)
Or if the file must already exist, failing if it doesn't:
Files.newBufferedWriter(outFilePath, StandardOpenOption.APPEND,
StandardOpenOption.WRITE)
To write a new file, failing if it already exists
Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE)

Keep getting cast exception error when I'm reading a data file? [duplicate]

This question already has answers here:
Why does writeObject throw java.io.NotSerializableException and how do I fix it?
(4 answers)
Closed 7 years ago.
So I'm trying to write and read a data file and declare a new variable of type 'GroceryStore' after I read the data file. I keep getting cast exception errors when I'm running my program. Could someone explain to me why this is happening and how I can fix it? Thanks.
Here's my write data file method:
{
FileOutputStream file = null;
ObjectOutputStream outStream = null;
file = new FileOutputStream(new File(filename));
outStream = new ObjectOutputStream(file);
outStream.writeObject(store1);
System.out.print(filename + " was written\n");
}
Here's my read data file method
{
FileInputStream file = null;
ObjectInputStream inStream = null;
file = new FileInputStream(new File(filename));
inStream = new ObjectInputStream(file);
GroceryStore newStore = (GroceryStore) inStream.readObject();
store1 = newStore;
System.out.print(filename + " was read\n");
}
At first glance at the code for reading it seems to want to put it to fast to the class GroseryStore, probably need some parsing before you can get it in there. Try to System.out.println the input from the reader, then you know what you have, then parse / chop and slice that into what you need / want of it.
So, second make a class for the read / write operations. As an example of how the write might work for simple text output file you could use something like this:
private String file_name = "FileName";
private String file_extention = ".txt";
BufferedWriter writer = null;
public void writeTextToFile(String stuff_to_file) {
// trying to write (and read) is a bit hazardous. So, try, catch and finally
try {
File file = new File(file_name + file_extention);
FileOutputStream mFileOutputStream = new FileOutputStream(file);
OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
writer = new BufferedWriter(mOutputStreamWriter);
writer.write(stuff_to_file); // and finally we do write to file
// This will output the full path where the file will be written to.
System.out.println("\nFile made, can be found at: " + file.getCanonicalPath());
} catch (Exception e) { // if something went wrong we like to know it.
e.printStackTrace();
System.out.println("Problem with file writing: " + e);
} finally {
try { // Close the writer regardless of what happens...
writer.close();
} catch (Exception e) { // yes, even this can go wrong
e.printStackTrace();
} // close try / catch
} // close finally
} // close method

java.nio.file.AccessDeniedException when reading a file

I want to read file content using this code:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
On some systems this file is not present or it's empty. How I catch this exception? I want to print message "No file" when there is no file and there is no value.
The AccessDeniedException can be thrown only when using the new file API. Use an inputStream to open a stream from the source file so that you could catch that exception.
Try with this code :
try
{
final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} catch(AccessDeniedException e) {
System.out.print("File access denied");
}
Try to use filter file.canRead()) to avoid any access exceptions.
Create a File object and check if it exists.
If it does then it's safe to convert that file to a byte array and check that the size is greater then 0. If it is convert it to a String. I added some sample code below.
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
I know it's not the one liner you were looking for. Another option is just to do
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
Read up on try catch blocks here like MrTux suggested, as well as java Files and java io here.

how can you delete a sound file in java?

I have a sound file that's recorded in my Java code and I need some code to delete it.
What is so special about sound file??!!!
You can use this code.
public static void deleteFile(String file){
File myFile = new File(file);
if (!myFile.delete()){
System.out.println("Deletion was not sucessful");
}else{
System.out.println("File deleted");
}
}
Since the answer is so obvious (file.delete()), I suspect that you're actually having issues with deleting it. I.e, file.delete() has returned false and the file is in reality not been deleted from the disk file system.
In that case, you can not delete it when you still have pointers open on that file. For example, when you have a InputStream or OutputStream on the file in your Java code, then you will not be able to delete the file as long as you do not call close() on the streams.
So, to fix that issue, you need to ensure that you call close() on any InputStream and OutputStream in the finally block of the try block where you're using the streams.
E.g.
File file = new File(name);
OutputStream output = null;
try {
output = new FileOutputStream(file);
// Write to output here ...
file.delete(); // Will always fail because output is not closed.
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
file.delete(); // Will succeed after close of output.

Categories

Resources