Home > Net >  Is there another library that can allow writing to a document (e.g. log) 'Date' types as F
Is there another library that can allow writing to a document (e.g. log) 'Date' types as F

Time:10-08

I have the following code and wanted information like date, count and true (Date, int and boolean types) to be written into my file (e.g. atm.log). Also, when I remove the Date and boolean type, the compiling goes through, but the file ends up not having the count number on it. I am not sure why it is not including the count number when the Date and boolean are left out as I have the 'close()' method.

Main:

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner;


public class Main {

    public static void main(String[] args) {
        try {
            File myObj = new File("atm.log");
            Scanner myReader = new Scanner(myObj);
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                System.out.println(data);
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        //while(true)
        //{
            ATM atm = new ATM();
            atm.init();
            atm.run();
        //}
    }
}

class:

import java.util.Date;
import java.util.ArrayList;

public class UserInfo
{
    private final Date date;
    private final int count;
    private final boolean correct;

    public UserInfo(Date date, int count, boolean correct)
    {
        this.date = date;
        this.count = count;
        this.correct = correct;
    }

    public Date getDate()
    {
        return date;

    }

    public int getCount()
    {
        return count;
    }

    public boolean isCorrect()
    {
        return correct;
    }
}

class:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.*;
import java.io.FileOutputStream;

public class Logger
{
    ArrayList<UserInfo> obj = new ArrayList<>();

    public Logger(Date date, int count, boolean correct){
        //obj.get(0).setValue(date,count, correct);
        obj.add(new UserInfo(date, count, correct));

        try (FileOutputStream out = new FileOutputStream("atm.log")) {


            for (UserInfo s : obj)//int i = 0; i < obj.size(); i  
                {
                out.write(s.getCount());
                out.write(s.getDate());
                out.write(s.isCorrect());
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

Error:

java: no suitable method found for write(java.util.Date)
    method java.io.FileOutputStream.write(int) is not applicable
      (argument mismatch; java.util.Date cannot be converted to int)
    method java.io.FileOutputStream.write(byte[]) is not applicable
      (argument mismatch; java.util.Date cannot be converted to byte[])

CodePudding user response:

Either you write to a stream (like FileoutputSteam) just the bytes. Or you let Java do the job of generating bytes and just write characters - but in this case you need to use a Writer. PrintWriter should be familiar to you - you use it during System.out.println(...)

try (
    OutputStream outstream = new FileOutputStream(...);
    PrintWriter out = new PrintWriter(outstream);
) {
    out.println(new Date());
}

CodePudding user response:

In general, writing to a file is format agnostic, that is, it's up to you. Can use things like JSON, XML, CSV, etc to apply common formats, but all these decisions add different levels of complexity.

So, for example, a simple solution might be to define a human readable format, for example...

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        Logger logger = new Logger();
        logger.log(LocalDateTime.now(), 100, true);
        logger.log(LocalDateTime.now(), 200, false);
        logger.log(LocalDateTime.now(), 300, true);
        logger.log(LocalDateTime.now(), 400, false);
        logger.log(LocalDateTime.now(), 500, true);

        logger.dump();
    }

    public class Logger {

        private ArrayList<UserInfo> obj = new ArrayList<>();
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd-HH:mm:ss");

        public Logger() {
        }

        public void log(LocalDateTime date, int count, boolean correct) {
            UserInfo info = new UserInfo(date, count, correct);
            obj.add(info);
            // You could keep the file open until the class in closed
            try (BufferedWriter bw = new BufferedWriter(new FileWriter("atm.log", true))) {
                String text = String.format("[%s] M %s", formatter.format(info.getDate()), info.getCount(), info.isCorrect() ? "Yes" : "No");
                bw.write(text);
                bw.newLine();;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        public void dump() {
            try (BufferedReader br = new BufferedReader(new FileReader("atm.log"))) {
                String text = null;
                while ((text = br.readLine()) != null) {
                    System.out.println(text);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class UserInfo {

        private final LocalDateTime date;
        private final int count;
        private final boolean correct;

        public UserInfo(LocalDateTime date, int count, boolean correct) {
            this.date = date;
            this.count = count;
            this.correct = correct;
        }

        public LocalDateTime getDate() {
            return date;

        }

        public int getCount() {
            return count;
        }

        public boolean isCorrect() {
            return correct;
        }
    }
}

Which will print something like...

[2021/10/08-08:46:15]  100 Yes
[2021/10/08-08:46:15]  200 No
[2021/10/08-08:46:15]  300 Yes
[2021/10/08-08:46:15]  400 No
[2021/10/08-08:46:15]  500 Yes

Some notes...

I've used LocalDateTime as a preference over Date, something we should be doing now days, but the basic concept will work with Date and SimpleDateFormatter.

It doesn't make sense that I need to create a new instance of Logger to add a new log entry, which then gets added to a List ... and each Logger instance is overwriting the previous file.

So, instead, I've create Logger to support multiple log outputs and to append to the file each time.

  •  Tags:  
  • java
  • Related