This project I'm working on, here is the function which write data's in to file :
public void writetofile(){
String bucky[]={custname,custlname,agee,address,id};
for(int i = 0; i < bucky.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("records.txt", true))) {
String s;
s = bucky[i];
bw.write(s);
bw.newLine();
bw.flush();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Error In File");
}
}
};
and there is another function defined which reads data's from file ,
public void filereader (){
int i=0;
Object[] options = {"OK"};
try
{
FileInputStream in = new FileInputStream("records.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
StringBuffer sb = new StringBuffer();
while((strLine = br.readLine())!= null)
{
sb.append(strLine +"\n");
}
JOptionPane.showMessageDialog( null, sb.toString());
}catch(Exception e){
JOptionPane.showOptionDialog(null, "Error", "Customers", JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
};
and the problem is , let's say I want to create an account for a customer in my project , so few questions were asked such as name , last name , gender , etc. and all those info's have been saved , but when I try to read files all the data's will appear in no format , I want them to be appear in the proper way like this :
customer name : Michelle ,
gender : Female ;
but right now it appears as this :
michelle ,
female ,
You can construct the desired output first and callbw.write(s); only once
or follow R.J 's suggestion. Put everything to an object and override toString methid of that class. This will be the perfect way of solving your problem
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Customer
{
private final String firstName;
private final String lastName;
private final String address;
private final int age;
private final int id;
public Customer(String firstName, String lastName, String address, int age,
int id)
{
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.age = age;
this.id = id;
}
#Override
public String toString ()
{
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", address=" + address + ", age=" + age + "]";
}
public static void main (String[] args)
{
}
public void writetofile (String custname, String custlname, int agee,
String address, int age)
{
Customer customer = new Customer(custname, custlname, address, age, id);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(
"records.txt", true)))
{
String s = customer.toString();
bw.write(s);
bw.newLine();
bw.flush();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error In File");
}
}
}
Related
Super simple program. Loop asking for student data (name, address, gpa) which is stored in a linked list. Output the data to a regular text file that can be opened in notepad.
I'm so close, but cannot figure out how to get my data written into the txt file. To start, here's my classes:
public class Student {
private String name;
private String address;
private double gpa;
public Student(String name, String address, double gpa) {
this.name = name;
this.address = address;
this.gpa = gpa;
}
public String getName() {
return this.name;
}
public String getAddress() {
return this.address;
}
public double getGpa() {
return this.gpa;
}
public String toString() {
return this.name + ", " + this.address + ", " + this.gpa;
}
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textLine)throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
In main I can get it to write the "Text to be written to file" into my .txt file, but I still can't figure out how to write studentData into that file.
public class Main {
public static void main(String[] args) throws IOException {
LinkedList < Student > studentData = new LinkedList < > ();
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.lineSeparator());
while (true) {
System.out.println("Student name: ");
String name = scanner.next();
if (name.isEmpty()) {
break;
}
System.out.println("Student address: ");
String address = scanner.next();
System.out.println("Student GPA: ");
double gpa = scanner.nextDouble();
studentData.add(new Student(name, address, gpa));
}
studentData.sort(Comparator.comparing(Student::getName));
for (Student info: studentData) {
System.out.println(info.getName() + "," + info.getAddress() + "," + info.getGpa());
}
String file_name = "C:\\Users\\hidden\\OneDrive - hidden\\Desktop\\Portfolio_Project.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[1]);
}
} catch (IOException e) {
System.out.println("Error. Please try again.");
}
// Write to a file
WriteFile data = new WriteFile(file_name);
data.writeToFile("Text to be written to file");
System.out.println("Text File Written To Portfolio_Project.txt on Desktop");
}
}
import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Enrolment{
public static void main(String[] args)
{
System.out.println("/*-------------------------------------");
System.out.println("My name: XIANGYU QIAO");
System.out.println("My student number: 5089864");
System.out.println("My email address: xq907#uowmail.edu.au");
System.out.println("Assignment number: 2");
System.out.println("-------------------------------------*/");
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
class Student{
private static Formatter outStream;
private static Scanner inStream;
public Student() throws IOException
{
outStream = new Formatter(new File("student1.txt"));
String fullName = "David Black";
String email = "davblk#ipw.edu.au";
String course = "1853E";
sNumber = 375428;
outStream.format("%s %s %s %i", fullName, email, course, sNumber);
outStream.close();
inStream = new Scanner( new File("student1.txt"));
String Fullname = inStream.next();
String Email = inStream.next();
String Course = inStream.next();
int Studentnumber = inStream.nextInt();
inStream.close();
}
public void displayStudInfo()
{
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
}
}
class Subject{
private static Formatter outStream;
private static Scanner inStream;
public Subject() throws IOException
{
outStream = new Formatter(new File("subject1.txt"));
String sCode = "CSIT455";
String session = "Autmn";
int year = 2017;
outStream.format("%s %s %i", sCode, session, year);
outStream.close();
inStream = new Scanner( new File("subject1.txt"));
String Subjectcode = inStream.next();
String Session = inStream.next();
int Year = inStream.nextInt();
inStream.close();
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
i am trying to create a file of student information and display it but i could not find a way to do that. could anyone help me to fix the code?
i am asked to display the student information in class Enrolment(main method here)and subject information that is given in class Student and Subject.i have no idea how to link these three things though it requires to use displayStudInfo method in class Student and displaySubjectInfo in class Subject.
If I correctly understand, you cannot access properties from constructor in displayStudInfo method. So assigning those properties to class properties will resolve the issue.
class Student {
private final String fullname;
private final String email;
private final String course;
private final int studentNumber;
public Student() throws IOException {
writeStudent();
Scanner inStream = new Scanner(new File("student1.txt"));
fullname = inStream.next();
email = inStream.next();
course = inStream.next();
studentNumber = inStream.nextInt();
inStream.close();
}
private void writeStudent() throws FileNotFoundException {
Formatter outStream = new Formatter(new File("student1.txt"));
outStream.format("%s %s %s %i", "David Black", "davblk#ipw.edu.au", "1853E", 375428);
outStream.close();
}
public void displayStudInfo() {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
}
If you do not want to add any more class prop, you will need to ad arguments to your method:
public void displayStudInfo( String fullname,String email,String course, int studentNumber) {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", 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");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (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");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
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;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
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());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
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");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
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;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}
I have a text file that looks like this.
BEGINNING OF LIST
Name: Janet
Age: 21
Birthday month: April
END OF LIST
BEGINNING OF LIST
Name: Peter
Age: 34
Birthday month: January
END OF LIST
So I want to grab info and put it into an object array. it is an extensive list and I am using the delimiters beginning of list and end of list to delimit the content.
How can I store these items in an object array?
I would suggest you create a class first for storing the information, with name, age, and birthday month attributes. It's a very good practice to override the toString() method so you can print out the class neatly.
Then you can check for each line whether it contains information about the name, age, or birthday month through splitting each line into an array of words, and checking for the information.
Once the line reads "END OF LIST", you can add a class Person with the parameters to the ArrayList.
For the example I used "people.txt" as the file (make sure you place the text document outside of the src folder which contains your .java files).
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
BufferedReader bufferedReader = null;
FileReader fileReader = null;
String name = null;
String age = null;
String month = null;
List<Person> people = new ArrayList<Person>();
try
{
String fileName = "people.txt";
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
String[] information = line.split(" ");
if (Arrays.asList(information).contains("Name:"))
{
name = information[1];
}
if (Arrays.asList(information).contains("Age:"))
{
age = information[1];
}
if (Arrays.asList(information).contains("month:"))
{
month = information[2];
}
if (line.equals("END OF LIST"))
{
people.add(new Person(name, age, month));
name = "";
age = "";
month = "";
}
}
for (Person person : people)
{
System.out.println(person);
System.out.print("\n");
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (IOException ex)
{
System.out.println("Error reading people.txt");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
if (fileReader != null)
{
try
{
fileReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
}
Person.java
public class Person {
private String name;
private String age;
private String birthday;
public Person(String name, String age, String birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}
#Override
public String toString()
{
String information = "Name: " + name + "\nAge: " + age + "\nBirthday: " + birthday;
return information;
}
}
So basically, I am doing this school project, and I have a super class called Person, and two subclasses (employees and clients) which extends class Person. When I run eighter subclass and for example when I add an employee, store the data in a .dat file, exit the program and re-run it, all the data stored before is set to a blank String. I hink that this is coming from the parameterless constructor in class Person, but that is the way I learnt to code it.
Super class:
import java.util.*;
public class Person{
String name, sname, dob, address, tel, mob;
public Person(){
name = ""; //I tried removing these statements, but then the data returned was null
sname = "";
dob = "";
address = "";
tel = "";
mob = "";
}
public Person(String name, String sname, String dob, String address, String tel, String mob){
this.name = name;
this.sname = sname;
this.dob = dob;
this.address = address;
this.tel = tel;
this.mob = mob;
}
Sub-class:
import java.io.*;
import java.util.*;
public class Employee extends Person implements Serializable{
private String empid;
private String valn = "[a-zA-Z ]+";
private String vala = "[a-zA-Z0-9, ]+";
private String valt = "[2][17][0-9]{6}";
private String valm = "[79][9][0-9]{6}";
private String valmm = "[7][7][0-9]{6}";
private String chkeid = "[0-9]{4}[E]";
public Employee(){
super();
empid = "";
}
public Employee(String name, String sname, String dob, String address, String tel, String mob,String empid){
super(name, sname, dob, address, tel, mob);
this.empid = empid;
}
public void setId(String empid){
this.empid = empid;
}
public String getId(){
return empid;
}
public String ToString(){
return "Emloyee Name: " + name + " " + sname + " " +
"\nAddress: " + address +
"\nDate of Birth: " + dob +
"\nTelephone Number: " + tel +
"\nMobile Number: " + mob +
"\nEmployee ID: " + empid;
}//Other methods...
Code for file saving:
File stock = new File("C:/Users/david/Desktop/Stock.dat");
File employee = new File("C:/Users/david/Desktop/Employee.dat");
File clients = new File("C:/Users/david/Desktop/Clients.dat");
try{
if(stock.exists() == true){
FileInputStream inFileStream = new FileInputStream (stock);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
stck = (Vector <Stock>)inObjectStream.readObject();
inObjectStream.close();
}else{
FileOutputStream outFile = new FileOutputStream(stock);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Stock Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!!");
sc.next();
}
try{
if(employee.exists() == true){
FileInputStream inFile = new FileInputStream (employee);
ObjectInputStream inObject = new ObjectInputStream(inFile);
emp = (Vector <Employee>)inObject.readObject();
inObject.close();
}else{
FileOutputStream outStr = new FileOutputStream(employee);
ObjectOutputStream outObj = new ObjectOutputStream(outStr);
outObj.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Employee Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!");
sc.next();
}
try{
if(clients.exists() == true){
FileInputStream in = new FileInputStream (clients);
ObjectInputStream inObjct = new ObjectInputStream(in);
clt = (Vector <Clients>)inObjct.readObject();
inObjct.close();
}else{
FileOutputStream out = new FileOutputStream(clients);
ObjectOutputStream outObjct = new ObjectOutputStream(out);
outObjct.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Clients Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!");
sc.next();
}
//at the end of the runner class.
try{
FileOutputStream outFile = new FileOutputStream(stock);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.writeObject(stck);
outObject.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}
try{
FileOutputStream outFile = new FileOutputStream(employee);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.writeObject(emp);
outObject.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}
try{
FileOutputStream outF = new FileOutputStream(clients);
ObjectOutputStream outObjct = new ObjectOutputStream(outF);
outObjct.writeObject(clt);
outObjct.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}
Employee is serializable, but Person is not. What that means is that the fields inherited from Person are not being serialized (that is, they are not being written to the ObjectOutputStream) and will not be filled in during deserialization (that is, reading from an ObjectInputStream).
The easiest way to fix this is to make Person implement Serializable. Note that the interface is inherited, so if you do make that change, you can safely remove implements Serializable from the Employee class.
If that isn't an option, you will have to do the work yourself in your Employee class. That's rather involved for someone new to Java, so I'd rather not clutter this answer with the details, but if you need to go this route I can elaborate.
Your code seems correct in terms of inheritence, the "problem" seems to be in the way you're using it.
How are you instanciating each employee?
Are you using the constructor with parameters? You have to use that one when you re-run your program, otherwise you'll be instantiating blank empoloyees as you describded.
To serialize members of super class this Person class should also implements Serializable.
public class Person implements Serializable {
...
As described here then Employee class will automatically implements Seralizable.