Java IO Create / Append File - java

Im trying to create a file if it doesnt exist, if it does exist append to it.
Is this the best way to do it? Im not sure having two try catches inside one method is good personally?
public static void main(String [] args)
{
String fileLocation = "/temp/";
String name = "Bob";
String timeStamp = "1988-03-15";
Path path = Paths.get(fileLocation+ "info.log");
if(!Files.exists(path)){
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
SimpleDateFormat tTimeFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
writer.write(tTimeFormatter.format(System.currentTimeMillis()) + " name: " + name + " Timestamp: "+ timeStamp);
writer.newLine();
} catch (IOException e) {
System.out.print(e.getStackTrace());
}
}

You can write to file with StandardOpenOptions: CREATE and APPEND.
Files.write(Paths.get(""), new byte[] {}, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
CREATE - means if file doesn't exists it creates new one otherwise get existing.
APPEND - means append new data to existing content in file.
So, you can do all your operations with a single line.

The File.createNewFile() method creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. This methods return a true value if the file is created successfully and false if the file already exists or the operation failed.
if (myFile.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}

Try using the printWriter class like this
java.io.PrintWriter p = new java.io.PrintWriter(yourFileHere);
// You can use println to print a new line if it allready exists
p.println(yourTextHere);
// Or append to the end of the file
p.append("TEXT HERE!!!!")

Related

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)

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

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

FileWriter not appending to existing file

I am writing a method that takes in a List of Twitter Status objects as a parameter, opens a log file containing String represenatations of Tweets, checks if any of the String representations of the Status objects are already written to the file - if so, it removes them from the list, if not it appends the Status to the file.
Everything is working up until I attempt to write to the file. Nothing is being written at all. I am led to believe that it is due to the method having the file open in two different places: new File("tweets.txt") and new FileWriter("tweets.txt, true).
Here is my method:
private List<Status> removeDuplicates(List<Status> mentions) {
File mentionsFile = new File("tweets.txt");
try {
mentionsFile.createNewFile();
} catch (IOException e1) {
// Print error + stacktrace
}
List<String> fileLines = new ArrayList<>();
try {
Scanner scanner = new Scanner(mentionsFile);
while (scanner.hasNextLine()) {
fileLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
// Print error + stacktrace
}
List<Status> duplicates = new ArrayList<>();
for (Status mention : mentions) {
String mentionString = "#" + mention.getUser().getScreenName() + " \"" + mention.getText() + "\" (" + mention.getCreatedAt() + "\")";
if (fileLines.contains(mentionString)) {
duplicates.add(mention);
} else {
try {
Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true));
writer.write(mentionString);
} catch (IOException e) {
// Print error + stacktrace
}
}
}
mentions.removeAll(duplicates);
return mentions;
}
I wrote here few thoughts looking your code.
Remember to always close the object Reader and Writer.
Have a look at try-with-resources statement :
try (Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true))) {
writer.write(mentionString);
} catch (IOException e) {
// Print error + stacktrace
}
To read an entire file in a List<String>:
List<String> lines = Files.readAllLines(Paths.get("tweets.txt"), StandardCharsets.UTF_8);
And again, I think it's a bad practice write in the same file you're reading of.
I would suggest to write in a different file if you don't have a particular constraint.
But if you really want have this behavior there are few alternative.
Create a temporary file as output and, when you process is successfully completed, than move it to the old one using Files.move(from, to).

Why AccessDeniedException is raising when using just created folder?

I'm creating simple object serialization, and creation of BufferedOutputStream is raising an exception AccessDeniedException. Here is the code:
Path filePath = Paths.get("c:\\temp\\");
File xmlFile = new File("c:\\temp\\");
boolean success = xmlFile.mkdirs();
if (!success && ! xmlFile.exists() ) {
// Directory creation failed
System.out.println("Failed to create a file: " + filePath);
}
try (
ObjectOutputStream objectOut = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(filePath, StandardOpenOption.WRITE)))){
// Write three objects to the fi le
objectOut.writeObject(solarSystem); // Write object
System.out.println("Serialized: " + solarSystem);
} catch(IOException e) {
e.printStackTrace();
}
But directory is empty and if it doesn't not exist, it's created...
I'll repeat my comment here: you seem to try to write to a directory not to a file. Try changing filePath to a file instead.

How to save the data into File in java?

I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.
Thanks,
vara kumar.pjd
Use a timestamp in the filename so you can be sure it is unique. Below example uses a timestamp in milliseconds which should be enough in most cases.
If you expect you can have multiple files within 1 millisecond then you could do something with a GUID/UUID. Note that GUID/UUID could result in duplicates too, however this chance is extremely rare.
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter(System.currentTimeMillis() + "out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You don't need to compute the filename by yourself, have a look at File.createTempFile.
From the javadoc:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this method was invoked, and
Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
A one liner. Using base 36 for the ids will make the file names shorter.
IOUtils.write(text, new FileWriter(Long.toString(System.currentTimeMillis(), 36)+".txt")));
http://commons.apache.org/io/
One solution can be, use a random number generator to generate a random number. Use this random number with some text as a filename. Maintain a list of already used names and each time you are saving the file, check through this list if the file name is unique.
One of possible ways to get File object with unique name could be:
public static File getUniqueFile(String base, String ext, int index) {
File f = new File(String.format("%s-%03d.%s", base, index, ext));
return f.exists() ? getUniqueFile(base, ext, index + 1) : f;
}
Update: and here goes basic usage/test case:
String s = "foo string\n";
FileWriter writer = null;
for (int i = 0; i < 10; i++) {
File f = getUniqueFile("out", "txt", 0);
try {
writer = new FileWriter(f);
writer.write(s);
writer.close();
writer = null;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
if (writer != null) { try { writer.close(); } catch (Exception e) {} }

Categories

Resources