Issue
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[])
Solution
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());
}
Answered By - Hiran Chaudhuri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.