ArrayList becomes null while writing to file - java

My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}

Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException

Related

How can I format the different sections of the input .txt in Java

I need to format the I/O text, which comes from a .txt file. I am able to print it, but I can't separate it in the different categories.
public class Main {
public static void main(String[] args) throws Exception {
class Recipe implements java.io.Serializable {
private String name, ingredients, steps;
public Recipe(String name, String ingredients, String steps) {
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
}
public String toString(){
return "dishName: " + name + " ingredients: " + ingredients + " steps: ";
}
}
Scanner input = null;
try {
//Choose the file that you will use.
input = new Scanner (new BufferedReader(new FileReader ("Root/src/recipes.txt")));
while ( input.hasNext() ) {
System.out.println(input.nextLine());
}
//Read your input and create the Objects Recipe
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null){
input.close();
}
} finally {
if (input != null){
input.close();
}
}
}
}
}

Reduce code duplication when reading different types of numbers from console

I have created three methods readLong, readInt and readDouble that basically does the same thing. Only difference is the method called by a scanner. How can I reduce duplicate code by turning them all to one method?
public long readLong(String description)
{
System.out.println(description);
long nrToReturn = 0;
boolean acceptedValue = false;
do {
System.out.println();
System.out.print("Choose one: ");
try
{
nrToReturn = consoleScanner.nextLong(); //Only line thats different except return value
acceptedValue = true;
}catch(Exception e)
{
acceptedValue = false;
consoleScanner.nextLine();
}
}while (!acceptedValue);
consoleScanner.nextLine();
return nrToReturn;
}
Here we go with one idea:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
private <T extends Number> T readType(String description, Class<T> desiredType) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.println();
System.out.print("Choose one: ");
try {
if (Integer.class.equals(desiredType)) {
result = new Integer(consoleScanner.nextInt());
} else if (Long.class.equals(desiredType)) {
result = new Long(consoleScanner.nextLong());
}
} catch(Exception e) {
consoleScanner.nextLine();
}
}
consoleScanner.nextLine();
return (T) result;
}
public long readLong(String description) {
return this.readType(description, Long.class);
}
public int readInt(String description) {
return this.readType(description, Integer.class);
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
t.readLong("Reading a long value...");
t.readInt("Reading an integer value...");
}
}
Update, following #Michu93 idea of a single transparent method:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
public <T extends Number> T readNumber(String description) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.print("\nChoose one: ");
String textRead = consoleScanner.next();
try {
result = new Integer(textRead);
} catch(Exception e1) {
try {
result = new Long(textRead);
} catch (Exception e2) {
try {
result = new Double(textRead);
} catch (Exception e3) {
}
}
}
consoleScanner.nextLine();
}
return (T) result;
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
for (int i = 0; i < 3; i++) {
Number input = t.readNumber(i + ": Reading int, long or double...");
System.out.println("Input class: " + input.getClass().getCanonicalName());
System.out.println("Input value: " + input);
}
}
}

ArrayList of objects sort using comparable

so I'm working on an address book assignment and I'm stuck on getting Comparable to sort the contacts by last name. I'm trying stuff that we haven't really learned like ArrayLists of objects, comparable and Serializable and comparable is confusing me the most.
Any tips on why the contacts aren't sorting? Second question, I wanted to try and make the first character of the first and last name an uppercase but I just couldn't figure it out so I made the whole thing uppercase in the toString method, any ideas how to get only the first char upper?
public class AddressBook implements Serializable{
private ArrayList<String> newBook = new ArrayList<String>();
private String dataFile;
private ArrayList<Contact> card =new ArrayList<Contact>(50);
private Contact[] contacts;
private int size = 0;
private int capacity = 0;
private String firstName;
private String lastName;
public static void main(String[] args) {
AddressBook AB = new AddressBook();
AB.addressBookMenu();
}
public void addressBookMenu() {
Scanner scan = new Scanner(System.in);
String option = "";
System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
System.out.println("\t add --> Add a new contact ");
System.out.println("\t find --> Find a contact ");
System.out.println("\t edit --> Edit an existing contact ");
System.out.println("\t view --> View the current address book");
System.out.println("\t save --> Save the current address book");
System.out.println("\t quit --> quit");
System.out.println();
option = scan.nextLine();
while(!(option.equalsIgnoreCase("quit"))) {
Contact con = new Contact(firstName, lastName);
if(option.equalsIgnoreCase("add")) {
System.out.println("Enter First Name: ");
String tempFirst = scan.nextLine();
System.out.println("Enter Last Name: ");
String tempLast = scan.nextLine();
con.setFirstName(tempFirst);
con.setLastName(tempLast);
card.add(con);
writeContact();
}
//View address book
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
Collections.sort(card);
con.getFullName();
readContact();
}
System.out.println();
System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
System.out.println("\t add --> Add a new contact ");
System.out.println("\t find --> Find a contact ");
System.out.println("\t edit --> Edit an existing contact ");
System.out.println("\t view --> View the current address book");
System.out.println("\t save --> Save the current address book");
System.out.println("\t quit --> quit");
System.out.println();
option = scan.nextLine();
}
}
public void writeContact() {
try (FileOutputStream out = new FileOutputStream("addressbook.txt")) {
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(card);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readContact() {
try (FileInputStream in = new FileInputStream("addressbook.txt")) {
ObjectInputStream is = new ObjectInputStream(in);
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
for(Contact temp : card) {
System.out.println(temp);
}
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Contact Class
public class Contact implements Comparable<Contact>, Serializable{
private String firstName;
private String lastName;
private String email;
private String phone;
public Contact() {
firstName = "";
lastName = "";
}
public Contact(String ln, String fn) {
lastName = ln;
firstName = fn;
}
public void setFirstName(String fn) {
firstName = fn;
}
public void setLastName(String ln) {
lastName = ln;
}
public void setFullName(String fn, String ln) {
firstName = fn;
lastName = ln;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return lastName + firstName;
}
public String toString() {
return
"FIRST NAME: " + getFirstName().substring(0).toUpperCase() + "\t" +
"LAST NAME: " + getLastName().substring(0).toUpperCase() + "\n";
}
#Override
public int compareTo(Contact nextContact) {
return lastName.compareTo(nextContact.lastName);
}
}
Your problem is as follows:
This code snippet
Collections.sort(card);
con.getFullName();
readContact();
is actually sorting the card collection you have, and then you call readContact() method which creates a local card collection inside it, which shadows the card collection you have in your main program, and prints its contacts, as they were written to the file before. they don't get sorted.
the solution would be like this:
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
con.getFullName(); // <------ ALSO, NOT QUITE SURE WHAT THIS IS FOR
readContact();
}
public void readContact() {
try (FileInputStream in = new FileInputStream("addressbook.txt")) {
ObjectInputStream is = new ObjectInputStream(in);
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
Collections.sort(card); // <----------- THIS ADDED
for(Contact temp : card) {
System.out.println(temp);
}
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any tips on why the contacts aren't sorting?
They are sorting. But then you don't print the sorted card.
You re-read the contacts in readContact and then print them, unsorted.
Probably you meant to write it this way instead:
if(option.equalsIgnoreCase("view")) {
System.out.println("\tADDRESS BOOK" + "\n" +
"=============================");
readContact();
Collections.sort(card);
printContacts();
}
And in readContact change this line:
ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();
To this:
card = (ArrayList<Contact>)is.readObject();
And move the printing out from readContact to its own method:
void printContacts() {
for(Contact temp : card) {
System.out.println(temp);
}
}
Second question, [...] any ideas how to get only the first char upper?
Sure, with a helper method like this:
private String toTitleCase(String name) {
return Character.toTitleCase(name.charAt(0)) + name.substring(1).toLowerCase();
}

How to call different remote objects on same interface method and maintain their own data? java RMI

I have server class which implements common interface between client and server. I have multiple remote objects bonded to different rim registry(diff ports and rim_id). Client will lookup the registry based on clientID for e.g. IF clientID is EXE1111 then it should connects to EXE server remote object. I want each server object to have its own hashtable to store data given by client. Here is server code::
enter code here
public class StationServers extends UnicastRemoteObject implements StationService{
private static final long serialVersionUID = 8119533223378875144L;
private String criminalRecordID="CR";
private String missingRecordID="MR";
private int count=11111;
protected StationServers() throws RemoteException {
super();
}
public static void main(String args[]){
try {
bindSPVMServer(new StationServers());
bindSPLServer(new StationServers());
bindSPBServer(new StationServers());
System.out.print("Servers are up and running on ");
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (Exception e) {
System.err.println("Server start up error: "+e.getMessage());
e.printStackTrace();
}
}
private static void bindSPVMServer(StationServers spvmObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPVM_RMI_PORT);
reg.bind(Constants.SPVM_RMI_ID, spvmObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPLServer(StationServers splObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPL_RMI_PORT);
reg.bind(Constants.SPL_RMI_ID, splObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPBServer(StationServers spbObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPB_RMI_PORT);
reg.bind(Constants.SPB_RMI_ID, spbObject);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void createCRecord(String firstName, String lastName,
String description, RecordStatus status) throws RemoteException {
}
#Override
public void createMRecord(String firstName, String lastName,
String address, String lastDate, String lastLocation,
RecordStatus status) throws RemoteException {
// TODO Auto-generated method stub
}
#Override
public String getRecordCounts() throws RemoteException {
// TODO Auto-generated method stub
return null;
}
#Override
public void editCRecord(String lastName, String recordID,
RecordStatus newStatus) throws RemoteException {
// TODO Auto-generated method stub
}
}
Client Code::
enter code here
public class OfficerClients implements Runnable{
public static void showMenu() {
System.out.println("\n****Welcome to DPIS****\n");
System.out.println("Please select an option (1-5)");
System.out.println("1. Create Criminal Record");
System.out.println("2. Create Missing Record");
System.out.println("3. Get Records Count");
System.out.println("4. Edit Record");
System.out.println("5. Exit");
}
public static void main(String[] args) {
try {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
new Thread(new OfficerClients()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private static RecordStatus getRecordStatus(String status, int userChoice) {
if (userChoice == 1) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else
throw new IllegalArgumentException("Invalid status for Criminal Record");
} else if (userChoice == 2) {
if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
else
throw new IllegalArgumentException("Invalid status for Missing Record");
} else if (userChoice == 3) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
}
throw new IllegalArgumentException("No Enum specified for this string");
}
private static StationService getRemoteObjectStub(String stationName) {
String url = "rmi://localhost:";
Remote lookup = null;
try {
if ("SPVM".equals(stationName))
url += Constants.SPVM_RMI_PORT;
else if ("SPL".equals(stationName))
url += Constants.SPL_RMI_PORT;
else if ("SPB".equals(stationName))
url += Constants.SPB_RMI_PORT;
url += "/" + stationName;
System.out.println("URL==" + url);
if (url != null && !url.isEmpty())
lookup = Naming.lookup(url);
} catch (Exception e) {
e.printStackTrace();
}
return (StationService) lookup;
}
#Override
public void run() {
int userChoice = 0;
String firstName = "", lastName = "", description = "", address = "", lastDate = "", lastLocation = "", badgeID = "", recStatus = "", recordID = "";
RecordStatus status;
String requestBadgeID = "Please enter your unique BadgeID: ";
String requestRecordID = "Please enter RecordID: ";
String requestFName = "First Name: ";
String requestLName = "Last Name: ";
String requestDesc = "Description of Crime: ";
String requestAddress = "Last Known Address: ";
String requestDate = "Date last seen: ";
String requestPlace = "Place last seen: ";
String requestStatus = "Status: ";
String requestNewStatus = "New Status: ";
showMenu();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
try{
while (true) {
Boolean valid = false;
System.out.print(requestBadgeID);
badgeID = br.readLine().toUpperCase();
System.out.println(badgeID);
String stationName = badgeID.replaceAll("[0-9]", "").trim();
System.out.println(stationName);
StationService server = getRemoteObjectStub(stationName);
while (!valid) {
try {
System.out.print("Enter your choice: ");
userChoice = Integer.parseInt(br.readLine());
valid = true;
} catch (Exception e) {
System.out
.println("Invalid Input, please enter an integer: ");
valid = false;
}
}
switch (userChoice) {
case 1:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestDesc);
description = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createCRecord(firstName, lastName, description,
status);
showMenu();
break;
case 2:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestAddress);
address = br.readLine().trim().toUpperCase();
System.out.print(requestDate);
lastDate = br.readLine().trim().toUpperCase();
System.out.print(requestPlace);
lastLocation = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createMRecord(firstName, lastName, requestAddress,
lastDate, lastLocation, status);
showMenu();
break;
case 3:
String recordCounts = server.getRecordCounts();
System.out.println(recordCounts);
showMenu();
break;
case 4:
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestRecordID);
recordID = br.readLine().trim().toUpperCase();
System.out.print(requestNewStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.editCRecord(lastName, recordID, status);
showMenu();
break;
case 5:
System.out.println("Have a nice day!");
br.close();
System.exit(0);
default:
System.out.println("Invalid Input, please try again.");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
I am new to RMI so I don't have any idea how to maintain each remote object and invoke based on client request and store records in hash table (per remote object).
please help...
You've described most of it yourself. Just create multiple instances of the remote object; bind each one into the Registry under a different name; have the client look up the appropriate name every time it wants that specific instance; and call the method via the stub that gets returned by that lookup.
Bingo.

Update text file method

I have a jtable that can be edite and then saved (updated) to a text file.
User select a line (that contains a book record) and request to borrow that book,
I use this method to update, But now when update, the old data is not deleted.
user_AllBooks uAllBooks = new user_AllBooks();
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == borrowButton) {
borrowInitialize(bTable.getSelectedRow());
}
public void borrowInitialize(int row) {
if (uAllBooks.getValueAt(row, 3).equals("Yes")) {
JOptionPane.showMessageDialog(null, "This Book Was Borrowed");
} else {
uAllBooks.setValueAt("Yes", row, 3);
uAllBooks.fireTableRowsUpdated(row, row);
uAllBooks.updateFiles(uAllBooks.bData);
}
}
...
}
public class user_AllBooks extends AbstractTableModel {
...
public void updateFiles(ArrayList<BookInformation> data) {
PrintWriter Bpw = null;
try {
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));
for (BookInformation bookinfo : data) {
String line = bookinfo.getBookID()
+ " " + bookinfo.getBookName()
+ " " + bookinfo.getBookDate()
+ " " + bookinfo.getBorrowStatus();
Bpw.println(line);
}
Bpw.close();
} catch (FileNotFoundException e1) {
} catch (IOException ioe) {
}
}
...
}
My BookInformation Class:
public class BookInformation {
private String BookName;
private String BookDate;
private String BookID;
private String BorrowStatus;
public String getBookName() {
return BookName;
}
public void setBookName(String book_name) {
this.BookName = book_name;
}
public String getBookDate() {
return BookDate;
}
public void setBookDate(String book_date) {
this.BookDate = book_date;
}
public String getBookID() {
return BookID;
}
public void setBookID(String Book_id) {
this.BookID = Book_id;
}
#Override
public String toString() {
return BookID + " " + BookName + " "
+ BookDate + " " + BorrowStatus + "\n";
}
public String getBorrowStatus() {
return BorrowStatus;
}
public void setBorrowStatus(String borrowStat) {
BorrowStatus = borrowStat;
}
}
Thanks.
Change this line
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));
to
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , false));
The second parameter (boolean) changes whether it should append the text file (add to the end of it) or just rewrite everything.
Source: Javadoc constructor summary for FileWriter:
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.

Categories