I have an arraylist of class Room which is held in class Hostel, i would like to write this arraylist to a text file. What is the most efficient method of doing so?
Hostel Class
public class Hostel
{
private ArrayList < Room > rooms;
}
Room Class
abstract class Room
{
public Room(int newRoomNo, boolean newRoomEnSuite, int newRoomNights, String newRoomBooker)
{
roomNo = newRoomNo;
roomEnSuite = newRoomEnSuite;
roomBooking = "Booked";
roomNights = newRoomNights;
roomBooker = newRoomBooker;
}
}
A one-liner from commons-io
FileUtils.writeLines(new File(path), list);
import java.io.*;
import java.util.ArrayList;
public class Hostel {
public void writeRooms(ArrayList<Room> rooms){
for (int i = 0; i < rooms.size(); i++) {
write(rooms[i]);
}
}
void write(Room room) throws IOException {
Writer out = new OutputStreamWriter(new FileOutputStream("FileName"));
try {
out.write(room.roomNo + ";" + roomEnSuite + ";" + roomBooking + ";" + roomNights + ";" + roomBooker + "/n");
}
finally {
out.close();
}
}
}
This should be a solution without using external API.
You can use ObjectOutPutStream to save all ArrayList
and can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. I
Try something along the lines of:
abstract class Room
{
public Room(int newRoomNo, boolean newRoomEnSuite, int newRoomNights, String newRoomBooker)
{
// ..
}
/* Each implementation of Room must be able to convert itself
into a line of text */
#Override
public abstract String toString();
}
class RoomWriter
{
public void write(List<Room> rooms, File file) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
try
{
for (Room room : rooms)
{
writer.write(room.toString());
writer.write("\n");
}
}
finally
{
writer.close();
}
}
}
Related
I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.
I have a 'Person' class where i stored data like name, surname etc. I make 5 object type Person, add them to ArrayList, and save this ArrayList to file. Next i'm loading from this file ArrayList and i have 5 person. Problem is when i want save again for example 10 object Person. When i'm loading ArrayList from file i'm getting only 5 person from first writing. If i repeat this still i will have load data from first writing to this file. How i can fix this ?
public class Data {
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons(5);
Data.loadPersons();
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
System.out.println("\n-----------\nNext Round\n-----------\n");
Data.savePersons(10);
Data.loadPersons();
}
/** Save a couple of Person Object to file C:/data.ser */
public static void savePersons(int noOfPersonToSave) throws IOException {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object and add them to ArrayList 'persons' for example */
for (int i = 0; i < noOfPersonToSave; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890" +i);
persons.add(personTest);
}
try {
fout = new FileOutputStream("C:\\data.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
} finally {
if (oos != null) {
oos.close();
}
}
}
/** Load previously saved a couple of Person Object in file C:/data.ser */
public static void loadPersons() throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("C:\\data.ser");
ois = new ObjectInputStream(fis);
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
} finally {
if (ois != null) {
ois.close();
}
}
}}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
new FileOutputStream("C:\\data.ser", true)
You're passing true for the append parameter. So you're appending a list of 10 persons to the file, after the already existing list of 5 people. And since you only read one list, you read the first you wrote, which contains 5 persons.
Pass false instead of true.
I have created a simple program that takes a title and a note which you enter then you have a choice to export the notes to txt file using BufferedWriter however because each note is a object which is stored in a ArrayList when storing them I iterate through a for enhanced loop it keeps duplicating each note as I iterate through all the object.
Note Class
import java.util.*;
public class Notes
{
private String notes;
private String titleOfNotes;
Scanner input = new Scanner(System.in);
public Notes()
{
titleOfNote(input);
takeNotes(input);
}
public void takeNotes(Scanner x)
{
System.out.println("Please Enter Your Note");
notes = x.nextLine();
}
public void titleOfNote(Scanner y)
{
System.out.println("Please Enter Title");
titleOfNotes = y.nextLine();
}
public String toString()
{
return "Title: " + titleOfNotes + "\t" + notes;
}
}
App Class //Does mostof the Work
import java.util.*;
import java.io.*;
public class App
{
private int exit = 0;
private int createANote;
private int displayTheNotes;
private int inputFromUser;
public boolean haveFileBeenWritten = true;
File file = new File("Notes.txt");
Scanner input = new Scanner(System.in);
ArrayList<Notes> arrayOfNotes = new ArrayList<Notes>();
public void makeNoteObject()
{
arrayOfNotes.add(new Notes());
}
public void displayAllTheNote(ArrayList<Notes> n)
{
for(Notes singleObjectOfNote : n)
{
System.out.println(singleObjectOfNote);
}
}
public void programUI(){
while(exit != 1)
{
System.out.println("1. Create A Note");
System.out.println("2. Display The Notes");
System.out.println("3. Exit");
System.out.println("4. Export to text file");
System.out.println("Enter Your Operation");
inputFromUser = input.nextInt();
if(inputFromUser == 1)
{
makeNoteObject();
}
else if(inputFromUser == 2)
{
displayAllTheNote(arrayOfNotes);
}
else if(inputFromUser == 3)
{
System.out.println("Exited");
exit = 1;
}
else if(inputFromUser == 4)
{
makeATxtFileFromNotes(arrayOfNotes);
System.out.println("Textfile created filename: " + file.toString());
}
else
{
System.out.println("You Select A Invalid Command");
}
}
}
public void makeATxtFileFromNotes(ArrayList<Notes> x)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
{
//Problem here!
for(Notes singleObjectOfNotes : x)
{
bw.write(singleObjectOfNotes.toString());
bw.newLine();
}
}catch(IOException e)
{
System.out.println("Cant Write File: " + file.toString());
haveFileBeenWritten = false;
}
}
public App()
{
programUI();
}
public static void main(String[]args)
{
App objectOfApp = new App();
}
}
I am new to Java so my code my not be the best!
If your problem is that you only need to see current list's Notes excluding the previous', it's because of this line:
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
By default, haveFileBeenWritten is true so based on the FileWriter API it will APPEND on the existing file Notes.txt so if you don't want that, change it to false.
Parameters:
file - a File object to write to
append - if true, then bytes will be
written to the end of the file rather than the beginning
EDIT: To access List<> elements, use get().
Example:
int size = myList.size();
for (int i = 0 ; i < size ; i++) {
//...
Notes note = myList.get(i);
//...
}
so i can't figure out how to print an arraylist index (the first index so 0) to a text file. Basically, I have a Job class which stores 5 variables
public class Job {
public int teamNo;
public String regNo;
public String gridRef;
public String gridCopy;
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
and then I have an arraylist of type Job:
private static ArrayList<Job> teamNoOne = new ArrayList<Job>();
So the data all gets added fine, prints it out etc but I can't save it to a text file. this is my code, I just get the random hash code of it but I need it in human readable form.
try {
File file = new File("JOBS-DONE-LOG.txt");
FileOutputStream fs = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fs);
System.out.println(teamNoOne.get(0));
os.writeObject(teamNoOne.get(0));
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Can't figure out how to do it.
writeObject serializes the object in your file, it doesn't write it in textual form (http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject(java.lang.Object))
You must do it in another way: for example, you can use the BufferedWriter class and the write method to write the output of your toString() method.
Here is a complete example:
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
public class Job {
public String regNo;
public String gridRef;
public String gridCopy;
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
public static void main(String[] args) throws Exception {
ArrayList<Job> teamNoOne = new ArrayList<Job>();
// fill your array
Job job = new Job();
job.regNo = "123";
// continue to fill the jobs...
teamNoOne.add(job);
BufferedWriter writer = new BufferedWriter(new FileWriter("JOBS-DONE-LOG.txt"));
System.out.println(teamNoOne.get(0));
writer.write(teamNoOne.get(0).toString());
os.close();
}
}
Since you are trying to save an arraylist of type Job, it has to be serialized (Refer this).
public class Job implements java.io.Serializable
{
public int teamNo=0;
public String regNo="default";
public String gridRef="default";
public String gridCopy="default";
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
}
For Saving the file
try
{
FileOutputStream fileOut = new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(teamNoOne);
out.close();
fileOut.close();
}
catch(IOException i)
{
i.printStackTrace();
}
Thus you can load the arraylist back like
Object o = null;
try
{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
o = in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
}
catch(ClassNotFoundException c)
{
c.printStackTrace();
}
Arraylist<Job> loaded_Job = (ArrayList<Job>) o;
Then print the arraylist
for(int i = 0; i < loaded_Job.size(); i++) {
loaded_Job.get(i).toString();
}
This happens because you didn't parameterize your ArrayList. Use generics when declaring your list:
ArrayList<Job> teamNoOne = new ArrayList<Job>();
Because now, though you have overriden your toString() method, teamNoOne.get(0) uses an Object's toString().
I have this arrayList in my UserArchive class, and a saveFile() method in my MainWindow class.
My problem is that every time I close the program all that shows in src/customerlist.txt is:
¨ÌsrUserArchiveYï≈ùÅ—ÀDLlisttLjava/util/ArrayList;xpsrjava.util.ArrayListxÅ“ô«aùIsizexpw
x.
Heres my code: Can anyone spot any problems?
public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();
public void regCustomer(User u) {
list.add(u);
}
public String toString() {
sorter();
String users = "";
Iterator<User> iterator = list.iterator();
while (iterator.hasNext()) {
users += iterator.next().toString() + "\n";
}
return users;
}
MainWindow class:
public class MainWindow extends JFrame {
private SaleWindow sW;
private UserArchive userA;
int customerID = 0;
////
public void saveFile() {
try {
FileOutputStream outStream = new FileOutputStream(
"src/customerlist.txt");
ObjectOutputStream utfil = new ObjectOutputStream(outStream);
utfil.writeObject(userA);
utfil.close();
} catch (NotSerializableException nse) {
JOptionPane
.showMessageDialog(this, "Objektet er ikke serialisert!");
} catch (IOException ioe) {
JOptionPane
.showMessageDialog(this, "Problem med utskrift til fil!");
}
}
Yes because ObjectOutputStream serializes objects in binary form. If you want serialize in some ASCII form try a JSON Serializer for example Jackson.
Please take a look at Javas serialization mechanismn. You're not writing the String content but the String objects (and the sourrounding list) in their binary form.
ObjectOutputStream is the wrong choice if all you want to do is write a plain text file. Take a closer look at java.io.FileWriter or java.io.PrintWriter.