I'm currently learning to develop a simple blockchain program that reads sample data from .txt and creates a new block for every 10 transactions. I was wondering if the given sample data was 23 lines of transactions, is there a way to make a new block that consist of the last 3 transactions ?
Current Output
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
What I want
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614520, prevHash=0, timestamp=1654785847387], tranx=Transaction [tranxLst=[alice|bob|credit|21.0, alice|bob|credit|22.0, alice|bob|debit|23.0]]]
my code:
Client app
public static void main(String[] args) throws IOException {
homework();
}
static void homework() throws IOException {
int count = 0;
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
tranxLst.add(line);
line = bf.readLine();
count++;
if (count % 10 == 0) {
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
}
bf.close();
}
Transaction class
public class Transaction implements Serializable {
public static final int SIZE = 10;
/**
* we will comeback to generate the merkle root ie., hash of merkle tree
* merkleRoot = hash
*/
private String merkleRoot = "9a0885f8cd8d94a57cd76150a9c4fa8a4fed2d04c244f259041d8166cdfeca1b8c237b2c4bca57e87acb52c8fa0777da";
// private String merkleRoot;
public String getMerkleRoot() {
return merkleRoot;
}
public void setMerkleRoot(String merkleRoot) {
this.merkleRoot = merkleRoot;
}
/**
* For the data collection, u may want to choose classic array or collection api
*/
private List<String> tranxLst;
public List<String> getTranxLst() {
return tranxLst;
}
public Transaction() {
tranxLst = new ArrayList<>(SIZE);
}
/**
* add()
*/
public void add(String tranx) {
tranxLst.add(tranx);
}
#Override
public String toString() {
return "Transaction [tranxLst=" + tranxLst + "]";
}
}
Block class
public class Block implements Serializable {
private Header header;
public Header getHeader() {
return header;
}
private Transaction tranx;
public Block(String previousHash) {
header = new Header();
header.setTimestamp(new Timestamp(System.currentTimeMillis()).getTime());
header.setPrevHash(previousHash);
String blockHash = Hasher.sha256(getBytes());
header.setCurrHash(blockHash);
}
/**
* getBytes of the Block object
*/
private byte[] getBytes() {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);) {
out.writeObject(this);
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Transaction getTranx() {
return tranx;
}
/**
* aggregation rel
*/
public void setTranx(Transaction tranx) {
this.tranx = tranx;
}
/**
* composition rel
*/
public class Header implements Serializable {
private int index;
private String currHash, prevHash;
private long timestamp;
// getset methods
public String getCurrHash() {
return currHash;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void setCurrHash(String currHash) {
this.currHash = currHash;
}
public String getPrevHash() {
return prevHash;
}
public void setPrevHash(String prevHash) {
this.prevHash = prevHash;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
#Override
public String toString() {
return "Header [index=" + index + ", currHash=" + currHash + ", prevHash=" + prevHash + ", timestamp="
+ timestamp + "]";
}
}
#Override
public String toString() {
return "Block [header=" + header + ", tranx=" + tranx + "]";
}
}
enter code here
Instead of using a counter in the conditional statement, try ForLoop.
static void homework() throws IOException {
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
for (int i = 0; i < 10; i++) {
tranxLst.add(line);
line = bf.readLine();
if (line == null) {
break;
}
}
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
bf.close();
}
Related
So I have a test which is to test the addNewCustomer method which does so by reading in from a text file
#Test
public void testAddNewCustomer() {
System.out.println("addNewCustomer");
try {
File nFile = new File("ProductData.txt");
File file = new File("CustomerData.txt");
Scanner scan = new Scanner(file);
ElectronicsEquipmentSupplier ees = new ElectronicsEquipmentSupplier(1, 1, InputFileData.readProductDataFile(nFile));
ees.addNewCustomer(InputFileData.readCustomerData(scan));
CustomerDetailsList expResult = ees.getDetails();
CustomerDetailsList result = ees.getDetails();
assertEquals(expResult, result);
} catch (IllegalCustomerIDException | IOException | IllegalProductCodeException e) {
fail(e.getMessage());
}
}
The problem that I'm having is to what to have as the expected result? I tried putting a string with the values that I thought would be entered but it then said I can't compare type string with type CustomerDetailsList. Any ideas?
public class CustomerDetailsList {
private final ArrayList<CustomerDetails> customerCollection;
public CustomerDetailsList() {
customerCollection = new ArrayList<>();
}
public void addCustomer(CustomerDetails newCustomer) {
customerCollection.add(newCustomer);
}
public int numberOfCustomers() {
return customerCollection.size();
}
public void clearArray() {
this.customerCollection.clear();
}
/**
*
* #param givenID the ID of a customer
* #return the customer’s details if found, exception thrown otherwise.
* #throws supplierproject.CustomerNotFoundException
*/
public CustomerDetails findCustomer(String givenID) throws CustomerNotFoundException {
CustomerNotFoundException notFoundMessage
= new CustomerNotFoundException("Customer was not found");
int size = customerCollection.size();
int i = 0;
boolean customerFound = false;
while (!customerFound && i < size) {
customerFound = customerCollection.get(i).getCustomerID().equals(givenID);
i++;
}
if (customerFound) {
return customerCollection.get(i - 1);
} else {
throw notFoundMessage;
}
}
#Override
public String toString() {
StringBuilder customerDets = new StringBuilder();
for (int i = 0; i < numberOfCustomers(); i++) {
customerDets.append(customerCollection.get(i).toString()).append("\n");
}
return customerDets.toString();
}
}
The list itself
Generally, you should test if the new customer is in the list. However, the expResult and result from your test are just the same, because at that point the ees already contains the new customer. Therefore the assertion does not make sense.
However, you can test if the Customer List contains the customer with given email (or some unique property of that customer).
I have a server application in Java, that holds a list of Student objects (implementing Serializable). The client application sends a message with an integer - index of Student object to fetch. Then the selected Student is sent to the client, the client modifies its value and sends back. The application however freezes at some point, and it's probably a problem with the lines I emphasized in the code below.
Server:
public class Server {
public static void main(String[] arg) {
ArrayList <Student> studentList = new ArrayList <Student> ();
studentList.add(new Student(170435, "justyna", "kaluzka", new ArrayList <Float>()));
studentList.add(new Student(170438, "michal", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170436, "marek", "polewczyk", new ArrayList <Float>()));
studentList.add(new Student(170439, "jakub", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170430, "anna", "majchrzak", new ArrayList <Float>()));
studentList.add(new Student(170425, "krzysztof", "krawczyk", new ArrayList <Float>()));
studentList.add(new Student(170445, "adam", "szydlowski", new ArrayList <Float>()));
studentList.add(new Student(170415, "karol", "chodkiewicz", new ArrayList <Float>()));
studentList.add(new Student(170465, "artur", "schopenhauer", new ArrayList <Float>()));
ServerSocket socketConnection = null;
ObjectInputStream serverInputStream = null;
ObjectOutputStream serverOutputStream = null;
try {
socketConnection = new ServerSocket(11111);
System.out.println("Server Waiting");
Socket pipe = socketConnection.accept();
serverOutputStream = new ObjectOutputStream( pipe.getOutputStream());
serverInputStream = new ObjectInputStream( pipe.getInputStream());
int index = serverInputStream.readInt();
System.out.println(index);
// HERE'S WHEN THE PROBLEM STARTS
serverOutputStream.writeObject(studentList.get(index));
Student student = (Student) serverInputStream.readObject();
System.out.println(student.toString());
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
serverInputStream.close();
serverOutputStream.close();
socketConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client:
public class Client {
public static void main(String[] arg) {
Student student = null;
Socket socketConnection = null;
ObjectOutputStream clientOutputStream = null;
ObjectInputStream clientInputStream = null;
try {
socketConnection = new Socket("127.0.0.1", 11111);
clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream());
clientInputStream = new ObjectInputStream(socketConnection.getInputStream());
clientOutputStream.writeInt(0);
student = (Student) clientInputStream.readObject();
student.setFamilyName("Konopnicka");
clientOutputStream.writeObject(student);
} catch (Exception e) {
System.out.println(e);
} finally {
try {
clientOutputStream.close();
clientInputStream.close();
socketConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My knowledge of client-server sockets is vague, so it's most likely a simple mistake. Any ideas?
EDIT:
Student class
public class Student implements Serializable {
private static final long serialVersionUID = -5169551431906499332L;
private int indexNumber;
private String name;
private String familyName;
private ArrayList<Float> marks;
private float average;
public Student(int indexNumber, String name, String familyName,
ArrayList<Float> marks) {
this.indexNumber = indexNumber;
this.name = name;
this.familyName = familyName;
this.marks = marks;
this.average = 0;
generateMarks();
calculateAverage();
}
public int getIndexNumber() {
return indexNumber;
}
public void setIndexNumber(int indexNumber) {
this.indexNumber = indexNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public float getAverage() {
return average;
}
public void setAverage(float average) {
this.average = average;
}
/**
* Calculates average of all Student's marks.
*/
public void calculateAverage() {
float sum = 0;
for (int i = 0; i < marks.size(); i++) {
sum += marks.get(i);
}
this.average = sum / marks.size();
}
/**
* Generates a random set of marks for the student.
*/
public void generateMarks() {
for (int i = 0; i < 10; i++) {
addMark(new Random().nextFloat() * 5);
}
}
/**
* Mark getter
*
* #return String representation of marks
*/
public String getMarks() {
String marksstr = "";
for (int i = 0; i < marks.size(); i++) {
marksstr += marks.get(i).toString() + " ";
}
return marksstr;
}
/**
* Adds a mark to the list.
*
* #param mark
*/
public void addMark(float mark) {
marks.add(mark);
}
#Override
public String toString() {
return "Index number:" + indexNumber + "\tName:" + name
+ "\tFamily name:" + familyName + "\t\tAverage:" + getAverage()
+ "\n";
}
}
Initialize your ObjectOutputStream before your ObjectInputSteam on your server.
When you initialize an ObjectInputStream, it waits for "header" data. Your server is waiting for that header data. You need to initialize your ObjectOutputStream first (which sends the header data), THEN your ObjectInputStream.
You can find more about this in here
You must flush your ObjectOutputStream after writing the int. When you write data to a stream, it gets written into a buffer. Data from that buffer is only sent when the stream's buffer is full. An int does not fill it, so you must flush() it to manually send the data from the buffer.
I need to get the line numbers a specific method is invoked in a .class file.
I took a look at How can I find all the methods that call a given method in Java? It returns the methods that call a method but I need the line numbers in the caller methods, as well.
I solved it by manipulating the code on that link a little
import java.io.InputStream;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.*;
public class App{
public static void main( String[] args ) {
try {
Test test = new Test();
test.findCallers();
}catch (Exception e){
e.printStackTrace();
}
}
}
class Test {
private String targetClass;
private Method targetMethod;
private AppClassVisitor cv;
class AppMethodVisitor extends MethodVisitor {
boolean callsTarget;
int line;
public AppMethodVisitor() {
super(Opcodes.ASM5);
}
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (owner.equals("Fibonacci") && name.equals("join") && desc.equals("()V")) {
callsTarget = true;
System.out.println("Function join called on " + this.line);
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
public void visitCode() {
callsTarget = false;
}
public void visitLineNumber(int line, Label start) {
this.line = line;
}
public void visitEnd() {
if (callsTarget){
System.out.println(cv.className + cv.methodName + cv.methodDesc + line);
}
}
}
class AppClassVisitor extends ClassVisitor {
private AppMethodVisitor mv = new AppMethodVisitor();
public String className;
public String methodName;
public String methodDesc;
public AppClassVisitor() {
super(Opcodes.ASM5);
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name;
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
methodName = name;
methodDesc = desc;
return mv;
}
}
public void findCallers() throws Exception {
InputStream stream = App.class.getResourceAsStream("Fibonacci.class");
ClassReader reader = new ClassReader(stream);
cv = new AppClassVisitor();
reader.accept(cv, 0);
stream.close();
}
}
Fibonacci.java content:
public class Fibonacci extends Thread{
int n;
int result;
public Fibonacci(int n){
this.n = n;
}
public void run(){
if((n == 0) || (n == 1)){
result = 1;
}else{
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
f1.start();
f2.start();
try{
f1.join();
f2.join();
}catch(InterruptedException e){
e.printStackTrace();
}
result = f1.getResult() + f2.getResult();
}
}
public int getResult(){
return result;
}
public static void main(String[] args) {
Fibonacci f1 = new Fibonacci(5);
f1.start();
try{
f1.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Answer is " + f1.getResult());
}
}
My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}
Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?
Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.
The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.
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.