Appending to a file is not working - java

I Couldn't write continuously to the file. I want to have a function that has to append to the file. But, I couldn't get what I need. Can anybody help me if there is any mistake with the code written.
void writeLog(String s)
{
try
{
String filename= "D:\\Gardening\\Logs.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write(s+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
Guys, I found the problem in the constructor of the class, The full code is here
Class Log
{
Log()
{
try{
FileWriter fw=new FileWriter("path of file");
}
catch(Exception a)
{
System.err.println(a);
}
}
void writeLog(String s)
{
try
{
String filename= "D:\\Gardening\\Logs.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write(s+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
As it was being called in the constructor again and again It was happening like that.

Just tested your code and it's working fine. Can you post your full code ? Also how are you calling the writeLog method.
public class Test {
void writeLog(String s) {
try {
String filename = "C:\\Temp\\Logs.txt";
FileWriter fw = new FileWriter(filename, true);
fw.write(s + "\n");
fw.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
public static void main(String[] args) {
Test t1 = new Test();
for (int i = 0; i < 5; i++) {
t1.writeLog("Hello");
}
}
}
This code creates a Logs.txt with the following content -
Hello
Hello
Hello
Hello
Hello

Try to create your FileWriter outside of the method where you call it and give it to your method as a second parameter.(If you will append strings to your file in whole project, you can create your FileWriter as singleton) There is no need to recreate FileWriter again and again.
By the way you should close FileWriter in finally block. Because in your code if an exception occured before close operation FileWriter cannot be closed. My code advice is like below:
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter(filename,true);
writeLog("Your String", fw);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
finally
{
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void writeLog(String s , FileWriter fw)
{
try
{
fw.write(s+"\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}

Related

Scanner has no next line although there is something in the file

I tried to scan a text file and rewrite it with one change. However, the scanner does not have a new line, although there is already something in the text file. What could be the reason?
public class ThemeStatus {
public void statusChanger(String subject, String name) {
PrintWriter fileWriter = null;
File themeFile = new File("FüFolder/Themenübersicht/" + subject + "/Settings.txt");
Scanner fileScanner = null;
try {
fileWriter = new PrintWriter(themeFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
fileScanner = new Scanner(themeFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(fileScanner.hasNextLine());
if(fileScanner.hasNextLine()) {
while(fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
if(line.contains("CurrentTheme")) {
fileWriter.println("CurrentTheme = " + name);
}
else {
fileWriter.println(line);
}
}
}
else {
fileWriter.println("CurrentTheme = " + name);
}
fileWriter.close();
}

Java Create File and Directory if needed

I want to create a file (outside of the workspace) so that everyone who opens my program has his own Textfile.
Currently I have to following Code:
private static final File m_dataFile = new File("C:\\temp\\MainPlayersLoginData.txt");
private static FileWriter writer;
private static Scanner reader;
public static void setMainPlayersLoginData(String name, String password) {
try {
if (!m_dataFile.exists()) {
createDirectory();
}
writer = new FileWriter(m_dataFile);
writer.write(name + "\n" + password);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void createDirectory() {
System.out.println("creating directory: " + m_dataFile.getName());
boolean result = false;
try {
m_dataFile.mkdirs();
result = true;
} catch (SecurityException se) {
}
if (result) {
System.out.println("DIR created");
}
}
With this code, the program creates a folder temp as planned, but creates a folder named "MainPlayersLoginData.txt" in it instead of a textfile. In addition I get a FileNotFoundException with the message "Access denied" when initialising the FileWriter.
I tried using m_datafile.mkdir() instead of m_datafile.mkdirs() but this time I get a FileNotFoundException with the message "The system cannot find the specified path" and the folder temp isnt created.
Edit: If i create the folder and the Textfile on my own, everything works fine.

OpenCSV all of the data storing in single line version (5.1) and data loss

Hi while saving object by using openCsv the data getting stored in a single line and if i try to add more than one object the data getting deleted of the previous object. please if anyone knows the solution answer it here.
public final Logger log=Logger.getLogger("Error");
public void beanToCsvExport(final T object, final String filePath) {
if(object == null) {
log.warning("Initialization of object failed");
}else {
try {
Writer writer = new FileWriter(filePath);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(object);
writer.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (CsvDataTypeMismatchException e) {
System.out.println(e.getMessage());
} catch (CsvRequiredFieldEmptyException e) {
System.out.println(e.getMessage());
}
}
}
When you try to write more than one object the last one is overwritten because the FileWriter you are passing to StatefulBeanToCsv is not in append mode. You should specify the append mode in the FileWriter constructor.
Writer writer = new FileWriter(filePath, true);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(object);
writer.close();
Edit: This should solve multiple columns headers and column header not breaking line. It works for me.
public <T> void beanToCsvExport(final List<T> object, final String filePath) {
if (object == null) {
System.out.println("Initialization of object failed");
} else {
try {
cleanFile(filePath);
FileWriter writer = new FileWriter(filePath, true);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(object);
writer.close();
} catch (IOException | CsvDataTypeMismatchException | CsvRequiredFieldEmptyException e) {
System.out.println(e.getMessage());
}
}
}
The function that resets the file:
public void cleanFile(String path) throws IOException {
FileWriter writer = new FileWriter(path); //Open as non-append to delete all data.
writer.write("");
writer.close();
}
To test the functions:
public void employeesToCsv() {
List<Employee> list = Arrays.asList(new Employee("101", "sunny"), new Employee("102", "Andrew"));
beanToCsvExport(list, "file.csv");
}
The achieved output:
"eId","eName"
"101","sunny"
"102","Andrew"

How to tell FileWriter to close any files before making a new file in Java

I have a buffered writer which is an instance of FileWriter in java. I have some functions which work like this:
private void a() {
try {
fileMaker("A");
bufferedWriter.write("x");
b();
bufferedWriter.write("z");
} catch (IOException e) {
}
}
private void b() {
try {
fileMaker("B");
bufferedWriter.write("b");
} catch (IOException e) {
}
private FileWriter bufferedWriter;
private void fileMaker(String fileName) {
try {
bufferedWriter = new FileWriter("./artifact/" + fileName + ".txt");
} catch (IOException e) {
System.out.println("there is something wrong in classFileMaker");
}
}
So my problem is, somehow after returning from function b I get a exception and can't write to file "A".
Any idea why?
fileMaker reuses the same bufferedWriter member, so every time you call it you lose the reference to the previous file's writer. A better design would be to return a new instance of a writer from the method and have the caller manage it:
private static FileWriter fileMaker(String fileName) throws IOException {
return new FileWriter("./artifact/" + fileName + ".txt");
}
private void a() {
try (FileWriter bufferedWriter = fileMaker("A")) {
bufferedWriter.write("x");
b();
bufferedWriter.write("z");
} catch (IOException e) {
}
}
private void b() {
try (FileWriter bufferedWriter = fileMaker("B")) {
bufferedWriter.write("b");
} catch (IOException e) {
}
}

Java read file with scanner

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

Categories

Resources