FileInputStream and OutputStream can't read and write objects into file - java

DESCRIPTION:
In my program, users are asked to input some values. The values get stored into an ArrayList so that I can print them out. Now the problem with this one is all data is lost once I terminate the program. That's why I have decided to store those arrayList object into file and and read them from there.
PROBLEM/QUESTION:
I have created all the related methods to write and read file. But it seems that no objects are written and read in file.The class I am mainly concerned about is ReadWrite.
Working code:
ReadWrite:
public void writeFile(List<PersonInfo> information) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
AboutPerson:
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
rw.writeFile(info);
info2=rw.readFile();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
PersonInfo:
........
........
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
.........
.........

package com.collection;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class PersonInfo implements Serializable{
private String name;
private int id;
private double credit;
public PersonInfo(){}
public PersonInfo(String name,int id,int credit)
{
this.name=name;
this.id=id;
this.credit=credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
class ReadWrite
{
public void writeFile(List<PersonInfo> information){
try {
FileOutputStream fos = new FileOutputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
}
public class AboutPerson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
int option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
rw.writeFile(info);
break;
case 2:
//display them
info2=rw.readFile();
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pinfo : info2) {
System.out.println(pinfo.getName()+"\t\t"+pinfo.getId()+"\t\t"+pinfo.getCredit());
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
}
}
Please implement serializable interface in PersonInf class.When u going to write object into file then u need to implement serializable interface other wise u will get exception like this:
java.io.NotSerializableException: com.collection.PersonInfo

first PersonInfo should implement SerialiZable,
and i'm not sure but PersonInfo should also have a default constructor

Related

Read data that has an integer and string in a text file - Java

I have read the file and it should print out the data on the console, but the problem is that I get this error message: Exception in thread "main" java.lang.NumberFormatException: For input string: "UNKNOWN". I've put the maximum length as an integer, but how do I put it as a string as well?
Here's what I have done so far:
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("people-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] peopleData = fileRead.split(":");
String commonName = personData[0];
String latinName = personData[1];
int maximumLength = Integer.parseInt(personData[2]);
Person personObj = new Person(commonName, latinName, maximumLength);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
System.out.println(personFile);
}
}
Person Class:
import java.util.*;
public class Person1 {
private String commonName;
private String latinName;
private int maximumLength;
public Person1(String personName, String latinName, int maximumLength) {
this.commonName = personName;
this.latinName = latinName;
this.maximumLength = maximumLength;
}
public String getCommonName() {
return commonName;
}
public String getLatinName() {
return latinName;
}
public int getMaximumLength() {
return maximumLength;
}
#Override
public String toString() {
return null;
}
}
Text File:
Alisha Khan:Cephaloscyllium ventriosum:100
Jessica Lane:Galeocerdo cuvier:UNKNOWN
Michael Brown:Sphyrna mokarren:600
...
This line in your input file:
Jessica Lane:Galeocerdo cuvier:UNKNOWN
is causing problem on this line in your code:
int maximumLength = Integer.parseInt(personData[2]);
because parseInt throws NumberFormatException on UNKNOWN. You need to decide what you want to do in this case. For example this code will keep maximumLength to default value -1 when an invalid integer is encountered:
int maximumLength = -1;
try {
int maximumLength = Integer.parseInt(personData[2]);
} catch (NumberFormatException e) {
}
You should teach your code your convention of UNKNOWN. Currently the code treats it as number.

Avoiding duplicate object properties

using a jframe i am trying to create a list of students, save them onto a file, re-read all those students and create new ones if, and only if, their id numbers are not the same. If the ID numbers are the same i am supposed to get an error message saying that that ID is already in use and thus not be able to register the new student. The only problem here is that even if the ID has already been used, it registers the students. What am i doing wrong?
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class NewEstudiantesJFrame extends javax.swing.JFrame {
public static List <Estudiantes> EstReg = new ArrayList<>();
public static Long ci, ciprueba;
public NewEstudiantesJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
private void AceptarButtonActionPerformed(java.awt.event.ActionEvent evt) {
Estudiantes estu = new Estudiantes();
try {
FileInputStream fis = new FileInputStream("t.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
EstReg = (List<Estudiantes>) ois.readObject();
ois.close();// es necesario cerrar el input stream
} catch (IOException | ClassNotFoundException ex) {
}
String NumId = new String();
String tipoId = (String) TipoIdBox.getSelectedItem();
estu.TipoId = tipoId;
NumId = NumIdField.getText();
if ((NumId.length()>9)||(NumId.length()<8)){
JOptionPane.showMessageDialog(null, "Please Type in the 8 or 9 ID digits");
a++;
NumIdField.setText(null);
//NumIdField.requestFocusInWindow();
}
else
{ ci = Long.parseLong(NumId);
}
try{
**for (Estudiantes e : EstReg){
if (e.NumId == Long.parseLong(NumId)){
JOptionPane.showMessageDialog(null, "ID already in use, please check your data");
NumIdField.setText(null);
NumIdField.requestFocusInWindow();
}
else {
estu.NumId = ci;
}**
}
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Inpult only ID numbers");
a++;
}
Here's my Estudiantes class
import java.io.Serializable;
public class Estudiantes implements Serializable{
String Nombre;
String Apellido;
String Direccion;
String Email;
String CursoActual;
String TipoId;
Long NumId;
String IdTotal;
String CodTel;
Long NumTel;
}
Thanks
Not sure if this will work but try using .compareTo() when comparing both of the longs instead of ==. Then check to see if the resulting value is equal zero.
https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html#compareTo-java.lang.Long-
Sorry my bad, i just realized i hadn't shown the rest of the code... Really sorry about that. I had to take a previous version of the same file and go with the .compareTo option. Thanks for the link Bryan Herrera.
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class NewEstudiantesJFrame extends javax.swing.JFrame {
public static List <Estudiantes> EstReg = new ArrayList<>();
public NewEstudiantesJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
private void AceptarButtonActionPerformed(java.awt.event.ActionEvent evt) {
Estudiantes estu = new Estudiantes();
try {
FileInputStream fis = new FileInputStream("C:\\t.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
EstReg = (List<Estudiantes>) ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException ex) {
}
String NumId = new String();
String nombre = new String();
String numTel = new String();
nombre = NombreField.getText();
String apellido = ApellidoField.getText();
String direccion = DireccionArea.getText();
String codtel;
boolean curso;
curso = false;
int a = 0;
String tipoId = (String) TipoIdBox.getSelectedItem();
estu.TipoId = tipoId;
if ((nombre.length()== 0)|| apellido.isEmpty()){
JOptionPane.showMessageDialog(null, "Please type in students full name");
a++;
}
else{
estu.Nombre = NombreField.getText();
estu.Apellido = ApellidoField.getText();
if (direccion.length()== 0){
JOptionPane.showMessageDialog(null, "Please input Student's address");
a++;
}
else{
estu.Direccion = DireccionArea.getText();}
}
try {
NumId = NumIdField.getText();
if ((NumId.length()!=8)){
JOptionPane.showMessageDialog(null, "Please type in the 8 digits if your ID");
a++;
NumIdField.setText(null);
else{
estu.NumId = Long.parseLong(NumId);
}
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Inpult only ID numbers");
a++;
}
for (Estudiantes es: EstReg){
if (es.NumId.compareTo(estu.NumId)==0){
JOptionPane.showMessageDialog(null,"ID already in use, please check your data");
NumIdField.setText(null);
a++;
}
}
try {
numTel = NumTelField.getText();
if (numTel.length()!=7){
JOptionPane.showMessageDialog(null, "Please type in the 7 telephone number digits");
a++;
}
else
estu.NumTel = Long.parseLong(numTel);
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Error. Only accepts numbers");
NumTelField.setText(null);
a++;
}
if (jRadioButton1.isSelected()){
estu.CursoActual= "Maths 1";
curso = true;
}
if (jRadioButton2.isSelected()){
estu.CursoActual ="Maths 2";
curso = true;
}
if (jRadioButton3.isSelected()){
estu.CursoActual ="Maths 3";
curso = true;
}
if ((curso == false) || (a > 0)){
JOptionPane.showMessageDialog(null, "Please finish filling the form out");
}
else{
ObjectOutputStream oos = null;
try {
JOptionPane.showMessageDialog(null, "Student succesfully registered. Thank you!");
estu.IdTotal = tipoId + NumId;
EstReg.add(estu);
FileOutputStream fos = new FileOutputStream("C:\\t.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(EstReg);
oos.close();
this.dispose();
} catch (Exception ex) {
}
}
}

Modify class to write exceptions to text file

I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

add multiple records in textfile

I want to add multiple records in a textfile. So I wrote the following program. But in this program data is overwrite every time user enters data from command prompt. In file data is overwrite. So How to add multiple records in a text file?
apples3.java
class apples3
{ public static void main(String[] args)
{ ffile g = new ffile();
g.get();
g.openFile();
g.addRecords();
g.closeFile();
}
}
ffile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{ private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{ x = new Formatter("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{ x.format("%s %s %s ", rollno, fname, lname);
}
public void closeFile()
{ x.close();
}
}
After adding a record i display it using the following code snippet:
Scanner x;
try
{ x = new Scanner(new File("Keyur.txt"));
while(x.hasNext())
{ String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
System.out.printf("%s %s %s %s\n", a, b, c, d);
}
x.close();
}
catch(Exception e)
{ System.out.println("could not find file");
}
the output of the display is as following in cmd:
1 ghi mno
2 xyz abc
3 pqr def
Actually i am running this program in my java frame. so i take all the necessary textbox, label, button. when i enter any name in textbox then that names' particular row i want to delete such as i enter xyz then delete row 2 xyz abc from database txt file.
and i write pqr in textbox and in second textbox aaa then i want to update that record in my txt file.
so if this possible then i want only code snippet then it is also useful for me.
Try opening the stream in append mode:
FileOutputStream fos = new FileOutputStream("xyz.txt", true);
x = new Formatter(fos);
According to Java Doc every time you create a Formatter object it will overwrite the file.You can see it here. Try this:
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{
private File file;
BufferedWriter output;
private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{
x = new Formatter();
file = new File("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{
try {
output = new BufferedWriter(new FileWriter(file,true));
output.write(x.format("%s %s %s \n", rollno, fname, lname).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile()
{
x.close();
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try using this
public void openFile() {
try {
// APPEND MODE SET HERE
bw = new BufferedWriter(new FileWriter("xyz.txt", true));
x = new Formatter(bw);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
x.format("%s %s %s", rollno, fname, lname);
x.format("%s", "\n");
}

How print list into file?

my question is short how write new class which will take info from main class List and print ir into a new file?
So this is my my ProgramTest class, which are main:
public class ProgramTest {
public static void main(String [] args)throws Exception {
//Autoriai
Author authorInf00 = new Author ("Mykolas", "Razma");
Author authorInf01 = new Author ("Lukas", "Brazukas");
Author authorInf02 = new Author ("Kristijonas", "Stoma");
//Knygos
Book bookInf00 = new Book ("Mykolas", "Razma", "Paukstis", 11111111, authorInf00);
Book bookInf01 = new Book ("Kristijonas", "Stoma", "gandras", 2222222, authorInf01);
Book bookInf02 = new Book ("Lukas", "Brazukas", "Varna", 3333333, authorInf02);
//Knygu listas
List <String> bookList = new ArrayList <String>();
bookList.add(bookInf00.getName() + " " + bookInf00.getIsbn() + " " + bookInf00.getFirstName() + " " + bookInf00.getLastName());
bookList.add(bookInf01.getName() + " " + bookInf01.getIsbn() + " " + bookInf01.getFirstName() + " " + bookInf01.getLastName());
bookList.add(bookInf02.getName() + " " + bookInf02.getIsbn() + " " + bookInf02.getFirstName() + " " + bookInf02.getLastName());
//Isveda i konsole Knygu lista
System.out.println("Knyga ISBN Vardas Pavarde");
for(int i=0; i < bookList.size();i++)
{
System.out.println(bookList.get(i));
}
//Sukuria instrukcija
Txt xce = new Txt();
//Paleidzia dirbti xml writeri
xce.runExample();
}
}
The second class is Library:
import java.util.List;
public class Library {
private List <String> bookList;
private DataWriter dataWriter;
public List <String> getBookList(){
return bookList;
}
public void exportBookList (List <String> bookList){
this.bookList = bookList;
}
public void setDataWriter(DataWriter dataWriter) {
this.dataWriter = dataWriter;
}
public DataWriter getDataWriter() {
return dataWriter;
}
}
DataWriter which should write info into file
import java.util.List;
public interface DataWriter {
public void dataWriterBook(List<String> bookList);
}
That is the problem: don't know how to write it correctly that it print my list into file.txt
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Txt {
public void runExample(){
System.out.println("Started .. ");
createDOMTree();
printToFile();
List <String> bookList;
System.out.println("Generated file successfully.");
}
public void dataWriterBook(List <String> bookList){
}
public void printToFile(){
try {
List<String> bookList = new ArrayList<String>();
// obviously you would want to use a list with stuff in it
BufferedWriter out = new BufferedWriter(
new FileWriter("C:/Users/jjegorovas/xml_failas.xml"));
for (String item : bookList){
out.write(item);
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can make a List of Books and then override the toString() methode.
For example:
class Book
{
private string name;
private string author;
private int id;
public Book(string name, string author, int id)
{
this.name = name;
this.author = author;
this.id = id;
}
public String toString()
{
return id + " - " + name + " - " + author; //Maybe use StringBuilder
}
}
class Main()
{
public static void main(String [] args)
{
Book book1 = new Book("Book1","James",1);
Book book2 = new Book("Book2","John",2);
Book book3 = new Book("Book2","Smith",3);
List<Book> bookList = new ArrayList<Book>();
bookList.add(book1);
bookList.add(book2);
bookList.add(book3);
saveBooksToFile(bookList);
}
public static void saveBooksToFile(List<Book> bookList)
{
//better use try-with-resource here
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("C:/Users/jjegorovas/xml_failas.xml"));
for (Book book : bookList){
out.write(book.toString());
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In ProgramTest.java, pass the bookList to Txt constructor as shown below:
//Sukuria instrukcija
Txt xce = new Txt( bookList); //pass bookList
//Paleidzia dirbti xml writeri
xce.runExample();
Modify Txt.java, as below (explanations in comments):
public class Txt {
List<String> bookList; //add a field to store the book list
public Txt(List<String> bookList) { //add a constructor method
this.bookList = bookList;
}
public void printToFile() { //modify this method
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"C:/Users/jjegorovas/xml_failas.txt")); //change extension from XML to TXT
for (String item : bookList) {
out.write(item);
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories