Where OpenCSV creates the .csv files? - java

I'm working with opencsv librarie in Eclipse and when I write something in a .csv I don't know in which folder is created. I should say that I need that the .csv file is not deleted when i turn off the app, so I can store in the assets folder, right?
My code is this:
try {
String csv = "data.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//Create record
String [] record = "hello,world".split(",");
//Write the record to file
writer.writeNext(record);
//close the writer
writer.close();
} catch (IOException e) {}

May be you can find it file at "/data/data/your_project_package_structure/files/data.csv"
Still don't find the You can do like this. file.getAbsolutePath() gives you full path there you can identify where your file getting stored:
try
{
File file = new File("data.csv");
// creates the file of name data.csv
file.createNewFile();
//you can print absolute path of file
System.out.println(file.getAbsolutePath());
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
//pass to csv writer
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//Create record
String [] record = "hello,world".split(",");
//Write the record to file
writer.writeNext(record);
//close the writer
writer.close();
} catch (IOException e) {
}

Related

Appending a line to an existing text file but adds an extra blank line

I am trying to add a new line to an existing text file, which works but sometimes adds a blank line in between the old data and the new data
So I have a file with the data:
mouse
keyboard
And when adding, it adds it like this:
mouse
keyboard
printer
but I don't want an empty line in between the old and new text.
This is the code I have used:
String filename= "Stock.txt"
FileWriter fw = new FileWriter(filename,true);
fw.write(System.lineSeparator() + data);
fw.close();
Buffer reader and Buffer writer are the preferred classes to use when reading and writing too and from files.
You can achieve this a few ways.
Example 1 - Using File, FileWriter and BufferWriter classes with manual close :
File file = new File("Stock.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data + "\n");
br.close();
fr.close();
Example 2 - Using File, FileWriter and BufferWriter classes with try-with-resource, which will auto-close the resource when processing has ceased :
File file = new File("Stock.txt");
try (FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(data + "\n");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file, file not found.");
} catch (IOException e) {
System.out.println("Unable to write to file." + file.getName());
}
See: https://stackabuse.com/reading-and-writing-files-in-java/ for some really useful info on reading and writing files!
See: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for info on try-with-resource.

How to write data to file on starting

I am using below code to write data in a file.
public static void writeDataToFile(final String fileName, final String fileContents) {
try {
File file = new File(Environment.getExternalStorageDirectory() + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(fileContents);
writer.flush();
writer.close();
} catch (IOException e) {
LogUtility.logInfo(TAG, e.getMessage());
}
}
Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help
You can set the append flag to false in the FileWriter constructor. Then, use the write() function instead of the append() function
FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
Why don't you remove the file if it exists:
if (!file.exists()) {
file.createNewFile();
} else {
file.delete()
file.createNewFile();
}
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one
Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.
StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
file.createNewFile();
} else {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
contentToWrite.append("\n\n" + sb);
file.delete();
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
PS: Don't forget to close FileReader and BufferedReader in a finally statement.

Java, write to file with headings

I have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.
I want to have headings on this file. How can I write the headlines to the file and only do it one time?
My method looks like this:
public static void writeToFile(String text) {
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter("test", true);
writer.write(text);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -
1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -
File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
//write heading
}
2. If the file is first time accessed then you can add a header -
String heading = "Some heading";
The full code looks like -
public static void writeToFile(String text) {
String heading = "Some heading";
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter(f, true);
if(f.exists() && !f.isDirectory()) {
writer.write(heading);
}
writer.write(text);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}finally{
writer.close();
}
}
You can use BufferWriter to write a sentence and take a look at a better way to handle the file.
try {
String content = "This is the content to write into file";
File f = new File("test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}finally{
writer.close();
}
}

How to overwrite an existing .txt file

I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}

how to append the written data to a file?

i am new developer in android.i would like to write some content to a file i have used a method to write into a file as follows
public void writeFile(String path,String text){
try{
Writer output = null;
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");
}
catch (Exception e) {
e.printStackTrace();
}
here i am passing path of a file and text to write.if i use in this way i can write the data but the previous data is losing.
how can i append or insert the latest text into a file without losing previous text?
Thanks in advance
Try this. Change this line ...
output = new BufferedWriter(new FileWriter(file));
to
output = new BufferedWriter(new FileWriter(file, true));
The true indicates that you want to append not overwrite
Have a look here and try:
new FileWriter(file, true);
the boolean indicates whether or not to append to an existing file.

Categories

Resources