Java — Log file only saving the latest item - java

I am writing an app in Java (new developer) and I am trying to save messages and things like that within a log file (logs/[date].txt). The problem I am getting is that it's overwriting each time, rather than appending the values to my file.
Here is my code:
public void onMessage(String channel, String nick, String account, String hostname, String message) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
try {
/* Check if the logs folder exists */
File logdir = new File("logs/");
boolean result = true;
if (!logdir.exists()) {
try {
logdir.mkdir();
}catch(Exception e){
System.err.println("[ERROR] Could not make directory 'logs/'");
result = false;
}
}
/* Check if the log file exists */
File fcheck = new File("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
if (!fcheck.exists()) {
try {
fcheck.createNewFile();
}catch (Exception e){
System.err.println("[ERROR] Could not make log file 'logs/" + sdfd.format(now).replace("/", "-") + ".txt'");
}
}
/* Write to file */
if (result) {
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
PrintWriter write = new PrintWriter(file);
String entry = "[" + sdf.format(now) + "] [" + channel + "] " + nick + " (" + account + ") > " + message + "\n";
write.append(entry);
write.close();
file.close();
}else{
System.err.println("[ERROR] Could not save line to log file.");
}
}catch (Exception e){
System.err.println("[ERROR] Could not save line to log file.");
}
}
Sorry if this isn't amazingly clear, but I'm still learning Java.
As you can see, I have write.append(entry); — which I thought would append \n to my log file, thus allowing me to save and save and keep all the entries.

You are closing the PrintWriter on every entry - a new instance is created everytime you call that method and the file is overwritten.
If you do not want to change this, you can set the FileWriter to append mode by using FileWriter(String, boolean).
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);
PrintWriter write = new PrintWriter(file);

When creating object of type File , add second parameter true , and the file will be appended
FileWriter fcheck = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt",true);

Set the append parameter of FileWriter to true:
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);

Related

FileReaders readLine return always null JAVA

Writing a program in java I'm trying to read the content of a file which is treated as a storage. I have a function to modify the amount of an object in the store, which is organized with one line per product, where the first word is the prodCode, and the second is the amount of it.
This is the function:
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
FileWriter toFile = new FileWriter(magazzino);
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
toFile.write(newContent);
toFile.close();
fromFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
And the result of it is that it won't enter the while cycle because the first readLine result null, though the file is correctly formatted, the 'amountRequest' function works properly and the input is correct.
Magazzino.txt:
1 12
3 25
4 12
You're probably having trouble because you're trying to read and write the file at the same time, with different file handles. I'd suggest reading the file first, then closing the FileReader, then creating a FileWriter to write to it.
The issue is that before you have read the contents of the file, you are creating an instance of FileWriter which will clear the file.
FileWriter toFile = new FileWriter("Magazzino.txt"); will clear the file
The solution is to just create the instance of FileWriter after you are done reading the file.
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
fromFile.close();
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
FileWriter toFile = new FileWriter(magazzino);
toFile.write(newContent);
toFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
You open a file twice, simultaneously for reading and writing.
As soon as you do this line,
FileWriter toFile = new FileWriter(magazzino);
your file is erased. Check it yourself.
Actually, with this line you are creating a new empty file for writing instead of the old one.
I'd suggest read file, then close, then write.
You can also try to pen file for append : new FileWriter("filename.txt", true);
This will not erase old file, allowing you to read it. But the new data will be appended to the end, though.
If you want to use you file as a state or storage, I'd suggest to look at sqlite: https://www.sqlite.org/index.html

Java Directory Search - Text File Writer - Only 1 result appears

Hey so I'm currently having an issue with this code: [There is more code to this but this is the block that I need help with]
File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" + "\\SearchResults.txt");
String customLoca = "C:\\Users\\" + System.getProperty("user.name") + "\\desktop";
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().contains(".jar"))
if (f.getName().endsWith(".jar"))
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}
}
I want it to print all the results however it only prints 1.
https://gyazo.com/406ab3039f3efa8f72d3dfff5732c088
Do you know a way I can make it so it prints all the results? Thanks.
The problem is that you are creating the file writer object inside loop. so it will replace the previous result hence only the last result will be present in the searchResults.txt.
To fix this problem move FileWriter fw = new FileWriter(fe); outside the for loop
Also note that you dont need both the 2 if conditions.
if if (f.getName().contains(".jar")) is true then
if (f.getName().endsWith(".jar")) also returns true, also you are missing the braces after the if statement.
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().endsWith(".jar")) {
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}

Is this correctly writing to a text file?

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java
Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

Buffered Writer overwriting file when not wanted

I have this code here that takes in 3 arguments, A Directory, a Filename, and a number. The program creates the filename in the directory and writes the number in it. So I can say...
>java D: myName.txt Clay 100
which will create a file named myName.txt in D: and says 100 in it.
If myName is taken up, it changes the name to myName(2), then myName(3) (if myName(2) taken up). The only problem is that when it changes the name to myName(2) and writes, it overwrites myName. I dont want it to overwrite myName, I want it to just create a new file with that name. Ive looked at similar questions and the common answer is the flush and close the writer which ive done And it still doesnt work.
Any help would be appreciated, here is my code so fart...
import java.io.*;
public class filetasktest{
public static void main(String[] args) throws IOException{
int i = 2;
String directory = args[0];
if (directory.substring(directory.length() - 1) != "/"){
directory += "/";
}
String contactName = args[1];
String contactNumber = args[2];
String finalDirectory = directory + contactName + ".contact";
File f = new File(finalDirectory);
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(finalDirectory), "utf-8"));
writer.write(contactNumber);
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally {
try {
writer.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
Your problem is here:
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
The renameTo method does not change the path of a File object; it renames a file on disk. The path of f stays the same throughout the loop: it starts out as D:/myName.txt and if a file by that name exists, the file is renamed as D:/myName(1).txt. The variable f still holds the path D:/myName.txt, which no longer names a file, and the content is written to D:/myName(1).txt, overwriting the previous content.
To fix this issue change the loop to:
while (new File(finalDirectory).exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
i++;
}
Take a look at FileInputStream(String, boolean) which will allow you to flag if the file should be appended or overwritten

Is my write text to file wrong?

I have a file call "CI.txt"
Inside the file the information is:
Mr Abc;ABC;abc123;Abc Road;428428;VISA;2222111144442222
Mr Efg;EFG;efg123;Efg Road;424213;MASTERCARD;4444555566667777
Mr Lmn;LMN;lmn123;Lmn Road;492482;VISA;9999000011112222
Here is my code, it works very well but the problem is..
for (Customer ci : custList){
//Compares the username and userpassword
//If correct, set new card number and card type..
if (inputUser.equals(ci.getUserName()) && inputPass.equals(ci.getPassword())) {
ci.setCardNo(newCardNo);
ci.setCardType(newCardType);
}
String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo();
try {
File fileCI = new File("CI.txt");
FileWriter fileWriter = new FileWriter(fileCI);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(text);
bw.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
catch (IOException e) {
System.out.println("Unable to write to file");
}
}
My output will only have the records of Mr Lmn. There is no record of Mr Abc whom I updated the new credit card type and number. Why is this happening? I did System.out.println(text) in the try statement and all was printed out properly. Anyone can help?
You are opening and closing the file in each iteration of the for-loop. Opening a file by default erases everything in it. You must open the file before starting the for-loop, and close it only afterwards.
The problem in your code that each for-loop iteration recreates the file and overwrites its content
You are building the Text and creating new file for each customer, so the last one override all the others:
for (Customer ci : custList){
//...
String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo();
try {
File fileCI = new File("CI.txt");
FileWriter fileWriter = new FileWriter(fileCI);
//...
}
You need to create the file outside the loop, then build the content and fill the file with data, and finally close the file.
The problem is that you are writing to the file inside the for loop. This means that with each loop, the file is overwritten with new data. In the end, only the last data is shown. You need to move the for-loop code inside the file-writing code, like this:
try
{
File fileCI = new File ( "CI.txt" );
FileWriter fileWriter = new FileWriter ( fileCI );
BufferedWriter bw = new BufferedWriter ( fileWriter );
for ( Customer ci : custList )
{
if ( inputUser.equals ( ci.getUserName () )
&& inputPass.equals ( ci.getPassword () ) )
{
ci.setCardNo ( newCardNo );
ci.setCardType ( newCardType );
}
String text = ci.getRealName () + ";" + ci.getUserName () + ";"
+ ci.getPassword () + ";" + ci.getContact () + ";"
+ ci.getcardType () + ";" + ci.getcardNo ();
bw.write ( text );
}
bw.close ();
fileWriter.close();
}
catch ( FileNotFoundException e )
{
System.out.println ( "File not found" );
}
catch ( IOException e )
{
System.out.println ( "Unable to write to file" );
}
You are running each customer in a loop.
for (Customer ci : custList){
Each time you run the loop, you create a new file called CI.txt
File fileCI = new File("CI.txt");
Since you create the file from scratch for every customer, only the last customer will remain. Open the file for append instead.
Use :
public FileWriter(File file,boolean append)
throws IOException
It says , append - if true, then bytes will be written to the end of the file rather than the beginning
Here is the API doc.

Categories

Resources