Testng to print result pass/ fail - java

Here, I am trying to print the results of testcases...
But whatever I do the test reult prints only as 16...
I want it to print as success or pass/ fail
It would be a great help if you could post a example.
public class EdiitAttendancePunchesByDepartment {
public EdiitAttendancePunchesByDepartment() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#BeforeMethod
public void setUp() {
}
#AfterMethod
public void tearDown() {
}
Boolean t = true;
#Test(priority = 0,dataProvider = "globalcfg")
public void global(String propid, String propvalue) throws IOException {
ConfigurationBean cfgbean = new ConfigurationBean();
for (ConfigurationModel cc : cfgbean.getConfigurationList()) {
if (cc.getPropertyId().equals(propid)) {
cc.setPropertyId(propid);
cc.setPropertyValue(propvalue);
System.out.println("Propid : " + cc.getPropertyId() + " value : " + cc.getPropertyValue());
}
}
File output = new File("D:/data/kishore/Edit_punches_output.xls");
FileWriter writes = new FileWriter(output.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(writes);
bw.write("EmpID-Date-Punch_Times-PayDay-Total_IN_Hours-OT-TEST_ID-Leave_Type");
bw.close();
cfgbean.setCreateButtonFlag(Boolean.FALSE);
cfgbean.setUpdateButtonFlag(Boolean.TRUE);
cfgbean.updateConfiguration();
cfgbean.retrieveConfiguration();
for (ConfigurationModel cc : cfgbean.getConfigurationList()) {
if (cc.getPropertyId().equals(propid)) {
System.out.println("Propid Out Put : " + cc.getPropertyId() + " value Out Put: " + cc.getPropertyValue());
}
}
System.out.println("Global Config running>>>>>>>>>>>>>>>");
boolean tr=Reporter.getCurrentTestResult().isSuccess();
System.out.println("Check<><><><><><><><><><><><><><><><><><><><>"+tr);
if(tr==true){
System.out.println("Result /////////////////////////////////////"+tr);
}
System.out.println("Test result>>>>>>>>>>>>>> "+Reporter.getCurrentTestResult().getStatus());
}
#Test(priority = 1,dataProvider = "viewpunches")
public void testviewpunches(String cmpcode, String orgcode, String Empid, String Empname, String deptname, Integer compgrpid,
String date, String Time1, String Time2, String type, String typeid) {
EditEmpTimeSheetBean bean = new EditEmpTimeSheetBean();
bean.setCmpCode(cmpcode);
bean.setOrgCode(orgcode);
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date1 = format.parse(date);
Date time1 = format1.parse(Time1);
Date time3 = format1.parse(Time2);
SimpleDateFormat op = new SimpleDateFormat("dd/MM/yyyy");
bean.setTimeSheetDate(date1);
bean.setEmpCompGroupId(compgrpid);
bean.setDepartmentName(deptname);
bean.setEmployeeCode(Empid);
bean.setEmployeeName(Empname);
bean.setDialogFlag(Boolean.TRUE);
bean.viewTimeSheetDetailByDepartment();
EmployeeDTO dto = new EmployeeDTO();
EmployeeService service = new EmployeeServiceImpl();
dto = service.retrieveEmployee(bean.getCmpCode(), bean.getOrgCode(), bean.getEmployeeCode());
if (dto == null) {
File output = new File("D:/data/kishore/Edit_punches_output.xls");
FileWriter write_new = new FileWriter(output, true);
BufferedWriter bw_new = new BufferedWriter(write_new);
bw_new.write("\n" + bean.getEmployeeCode() + "- NO record found - - - - -" + typeid);
bw_new.close();
System.out.println("Invalid Employee Code");
} else {
System.out.println("Valid code");
}
for (EmpWorkLogModel cc : bean.getEmpWorkLogArray()) {
if (cc.getEmployeeCode().equals(Empid)) {
cc.onChange();
List<LogTimeModel> kl = new ArrayList<LogTimeModel>();
LogTimeModel m = new LogTimeModel();
LogTimeModel mn = new LogTimeModel();
m.setPunchTimes(time1);
if (type.equalsIgnoreCase("insert")) {
m.setOpFlag(Constant.OP_FLAG_INSERT);
}
if (type.equalsIgnoreCase("update")) {
m.setOpFlag(Constant.OP_FLAG_UPDATE);
}
if (type.equalsIgnoreCase("delete")) {
m.setOpFlag(Constant.OP_FLAG_DELETE);
}
mn.setPunchTimes(time3);
if (type.equalsIgnoreCase("insert")) {
mn.setOpFlag(Constant.OP_FLAG_INSERT);
}
if (type.equalsIgnoreCase("update")) {
mn.setOpFlag(Constant.OP_FLAG_UPDATE);
}
if (type.equalsIgnoreCase("delete")) {
mn.setOpFlag(Constant.OP_FLAG_DELETE);
}
if (type.equalsIgnoreCase("CHANGE")) {
}
kl.add(m);
kl.add(mn);
cc.setPunchList(kl);
System.out.println("punch time>>>>>>>>>>>>>>>>>XXXXXXXXX>>>>>>>>>>>>XXXXXXXXXX " + mn.getPunchTimes() + " " + cc.getPunchTime() + " " + cc.getFromDate());
System.out.println("Emp ID : " + cc.getEmployeeCode() + " \nPunch time : " + cc.getPunchTimes() + " \nPay Day : " + cc.getPayDay() + " \nIN hours: " + cc.getWorkedTime());
} else {
System.out.println("\n\nNo Records found for : " + cc.getEmployeeCode());
}
}System.out.println("Test result>>>>>>>>>>>>>> "+Reporter.getCurrentTestResult().getStatus());
bean.updateLogTime();
testview(bean.getEmployeeCode(), bean.getEmployeeName(), bean.getShiftId(), date, typeid);
} catch (Exception e) {
System.out.println(" Error :" + e);
e.printStackTrace();
}
}
This is the output i receive
sessionFactory1 org.hibernate.internal.SessionFactoryImpl#196a6ac
sessionFactory1 SessionStatistics[entity count=0collection count=0]
Propid : com.rgs.payroll.enableDynamicWeekOff value : N Propid Out Put
: com.rgs.payroll.enableDynamicWeekOff value Out Put: N Global Config
running> Check<><><><><><><><><><>false Test result>>>>>>>>>>>>>> 16

Remove pass fail decision making code from ur test case and use the below code:
#AfterMethod
public void tearDown(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
System.out.println(result.getMethod().getMethodName()+ " is failed");
//do something here.
}
}

16 means "STARTED".
It's the only value you can expect into the test itself.
TestNG will only determine the value after the end of the method.
You can try to print the result from the #AfterMethod method.

Related

How to make RestAssured.filters() Thread Safe?

I am using RestAssured for my API Automation and I am using ExtentReports to log the request and response. It works fine when I run in a single thread. But when I run in multiple threads, it doesn't seem to be thread-safe. Logs of one thread are getting clogged in the other. Below is my TestList Class:
TestListClass.Java
public class TestListener implements ITestListener, ISuiteListener {
String line = new String(new char[150]).replace('\0', '-');
ExtentReportHelper report;
ExtentReports extent;
ExtentTest test;
private StringWriter requestWriter;
private StringWriter responseWriter;
private PrintStream printRequestStream;
private PrintStream printResponseStream;
#Override
public void onTestStart(ITestResult result) {
log.info("\n");
log.info(line);
log.info(StringUtils
.center("Test case :--> \"" + result.getName() + "\" <--: about to start...", 130));
log.info(line + "\n\n");
test = extent.createTest(result.getName());
apiLogsReport();
}
private void apiLogsReport() {
requestWriter = new StringWriter();
responseWriter = new StringWriter();
printRequestStream = new PrintStream(new WriterOutputStream(requestWriter,"UTF-8"));
printResponseStream = new PrintStream(new WriterOutputStream(responseWriter,"UTF-8"));
RequestLoggingFilter requestLoggingFilter = new RequestLoggingFilter(printRequestStream);
ResponseLoggingFilter responseLoggingFilter = new ResponseLoggingFilter(printResponseStream);
RestAssured.filters(requestLoggingFilter, responseLoggingFilter);
}
#Override
public void onTestSuccess(ITestResult itr) {
log.info(line);
log.info(StringUtils.center(String.format("|%30s|", itr.getTestClass())
+ String.format("|%20s|", itr.getName()) + String.format("|%10S|", "passed"), 120));
log.info(line + "\n");
test.log(Status.PASS,
MarkupHelper.createLabel(itr.getName() + " PASSED ", ExtentColor.GREEN));
printRequestStream.flush();
printResponseStream.flush();
report.logRequestResponse(test, requestWriter, responseWriter);
}
#Override
public void onTestFailure(ITestResult itr) {
log.info(line);
log.info(StringUtils.center(String.format("|%30s|", itr.getTestClass())
+ String.format("|%20s|", itr.getName()) + String.format("|%10S|", "failed"), 120));
log.info(line + "\n");
test.log(Status.FAIL, MarkupHelper.createLabel(itr.getName(), ExtentColor.RED));
test.fail(itr.getThrowable());
printRequestStream.flush();
printResponseStream.flush();
report.logRequestResponse(test, requestWriter, responseWriter);
}
#Override
public void onTestSkipped(ITestResult itr) {
log.info(line);
log.info(StringUtils.center(String.format("|%30s|", itr.getTestClass())
+ String.format("|%20s|", itr.getName()) + String.format("|%10S|", "skipped"), 120));
log.info(line + "\n");
test.log(Status.SKIP,
MarkupHelper.createLabel(itr.getName() + " SKIPPED ", ExtentColor.ORANGE));
test.skip(itr.getThrowable());
printRequestStream.flush();
printResponseStream.flush();
report.logRequestResponse(test, requestWriter, responseWriter);
}
#Override
public void onStart(ITestContext context) {
report = new ExtentReportHelper();
extent = report.initReport(testNgHelper);
}
logRequestResponse method()
public void logRequestResponse(ExtentTest test, StringWriter requestWriter, StringWriter responseWriter) {
String[] requests = requestWriter.toString().split("Request method:");
String[] responses = responseWriter.toString().split("HTTP/1.1");
for (int i = 1; i < requests.length; i++) {
test.log(Status.INFO, "<pre>Request: " + requests[i] + "\nResponse: " + responses[i] + "</pre>");
}
}
Am I doing something wrong? Or doesn't RestAssured filters support multi-threaded execution? Please help me out if there is any other way to do so if it is not thread-safe.

Println method doesn't work on second run

So my Kiir method doesn't work since my last run. The program should write the new values to a .txt file, and give it back the whole text with the new value included.
The program says the issue is in the
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
but I can't see the problem. Any idea?
public class VizsgaMintaA {
static SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
static Scanner sc= new Scanner(System.in);
/**
* #param args the command line arguments
* #throws java.text.ParseException
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws ParseException, FileNotFoundException {
ArrayList<Versenyzo> versenyzok = new ArrayList<>();
Feltolt(versenyzok);
Kiir(versenyzok);
Ujversenyzo(versenyzok);
Kiir(versenyzok);
Fajlbair(versenyzok);
}
private static void Feltolt(ArrayList<Versenyzo> versenyzok) throws ParseException{
Versenyzo v = null;
File f = new File("versenyzok.txt");
try {
Scanner scan = new Scanner(f, "iso-8859-2");
while (scan.hasNextLine()) {
String sor = scan.nextLine();
String[] adatok = sor.split(";");
if (adatok.length == 3) {
v = new Versenyzo();
v.nev = adatok[0];
v.szuletes = df.parse(adatok[1]);
v.csapat = adatok[2];
} else if (adatok.length > 3) {
v = new Versenyzo (adatok[0],df.parse(adatok[1]),adatok[2]
,Integer.parseInt(adatok[3])
);
}
versenyzok.add(v);
}
} catch (FileNotFoundException ex) {
System.out.println("Nincs meg a fájl.");
}
}
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
}
private static void Ujversenyzo(ArrayList<Versenyzo>versenyzok)throws ParseException{
Versenyzo v = new Versenyzo();
System.out.println("Adjon meg egy nevet:");
v.nev=sc.nextLine();
System.out.println("Adja meg a születési idejét:");
v.szuletes=df.parse(sc.nextLine());
System.out.println("Adja meg a csapatot:");
v.csapat = sc.nextLine();
System.out.println("Adja meg a vb címek számát:");
v.vbcim = sc.nextInt();
versenyzok.add(v);
}
public static void Fajlbair(ArrayList<Versenyzo>versenyzok) throws FileNotFoundException {
PrintStream f2 = new PrintStream(new File ("versenyzok2.txt"));
for (Versenyzo v : versenyzok){
f2.println(v.toString());
}
}
}
class Versenyzo {
String nev,csapat;
Date szuletes;
int vbcim;
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
#Override
public String toString(){
return "Versenyzo:" +nev + " Született:" + df.format(szuletes)+" Csapata:"+ csapat + " Vb címek:" + vbcim;
}
public Versenyzo(String nev, Date szuletes, String csapat, int vbcim) {
this.nev = nev;
this.szuletes = szuletes;
this.csapat = csapat;
this.vbcim = vbcim;
}
public Versenyzo(){
}
}
First check if the list passed to Kiir() is null:
public static void Kiir(ArrayList<Versenyzo> versenyzok){
if (versenyzok == null)
return;
for (Versenyzo f : versenyzok){
System.out.println(f);
}
}
I did make another change to Kiir().
I removed toString() from f.toString(), since you have overridden it, it is redundant.
Now the only problem with your implementation of the toString() method inside the Versenyzo class is if there exist null values in the szuletes property.
If this is the case then change to this:
#Override
public String toString(){
return "Versenyzo:" + nev + " Született:" + (szuletes == null ? "null" : df.format(szuletes)) + " Csapata:" + csapat + " Vb címek:" + vbcim;
}

Handling a .data file with uneven whitespaces delimited and populate to an bean object using java program

How to handle file data as shown below, which is delimited by uneven whitespaces, where if tokenizer is used based on space, it'll give tokens which cannot be assigned to java bean fields directly.
Below is the content Data of cheapdata4.data:
(TX 260816.<
0954F2003EGGPLEIBLNX37PU ZC550 Z <CA C A L L8 STAF P18 UL15 KIDL
0001F0148BIKFEDDSGWI2797 ZA319 Z <CATGWI2 C M V104 GMH4 GMH UL60 EDDS
4893F1416EGPGEGHFGJOID ZSR20 Z <AAEGPGD C A LT TLA DCS L612 N859 Q41
7945F1400EGSHEGCCLOG63JF ZD328 Z <(A C A R L OTBE Y70 EGCC
7946F1647EGSHEGGWAZE01F ZE50P Z <(A C A R LT MAM1 LAPR ABBO BKY2
7947F1701EGSHEGCCLOG63JF ZD328 Z <(A C A R L / MAM0 OTBE POL ROSU
4368F1657ESSBEGGWBLJ59BF ZC56X Z <RAUBLJ5 A LT UN86 UP7 UP25 EGGW
4369F1728ESSBEGCCETI226L MLJ45 012<RAUETI2 A L UL97 Y70 EGCC
4370F0551LHBPEGGWWZZ196 ZA321 Z <RAUWZZ1 A MT UL60 UY6 UM20 EGGW
7950END 260816.<
package com.msa.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.msa.bean.CheapData;
public class FinalParser {
public static void main(String[] args) {
BufferedReader reader;
try {
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(
new FileReader(
"C:\\Users\\Desktop\\assignment\\cheapdata4.data"));
System.out.println("Reading file...");
String line = reader.readLine();
line = line.replaceAll("\\s{2,}", " ");
String[] toks = line.replace(" ", ",").trim().split(",");
line = line.replaceAll("\\s{2,}", " ");
String[] headerTokens = line.split(" +");
String fileStartDate = headerTokens[1].substring(0, 6);
List<String> cheapDataContent = new ArrayList<>();
String[] lineTokens = { "" };
CheapData cheapFileDets = null;
List<CheapData> cheapDataList = new ArrayList<>();
while (line != null) {
line = reader.readLine();
line = line.replaceAll("\\s{2,4}", " ");
// line = line.replaceAll("\\s{2}", " NA ");
// line = line.replaceAll(" ",", ");
// line = line.replaceAll("\\,{2}", "");
lineTokens = line.split(" +");
int len = lineTokens.length;
// String fileEndDate ="";
if (len == 2) {
String fileEndDate = lineTokens[1].substring(0, 6);
if (fileStartDate.equals(fileEndDate)) {
break;
} else {
System.out.println("Date mismatch...");
}
}
if (len >= 6) {
cheapFileDets = new CheapData();
String lineNum = lineTokens[0].substring(0, 4);
cheapFileDets.setLineNum(lineNum);
String cheapReference = lineTokens[0].substring(4);
cheapFileDets.setCheapReference(cheapReference);
cheapFileDets.setDate(fileStartDate);
cheapFileDets.setAircraftCode(lineTokens[1]);
cheapFileDets.setIdentifierCode(lineTokens[2]);
cheapFileDets.setLicenseCode(lineTokens[3]);
if (lineTokens[4].equals("C"))
cheapFileDets.setCodeOne(lineTokens[4]);
else
cheapFileDets.setCodeOne(null);
if (lineTokens[5].equals("A"))
cheapFileDets.setCodeTwo(lineTokens[5]);
else
cheapFileDets.setCodeTwo(null);
if (lineTokens[6].equals("R"))
cheapFileDets.setCodeThree(lineTokens[6]);
else
cheapFileDets.setCodeThree(null);
} else {
if (len == 7)
cheapFileDets.setIdCode(lineTokens[7]);
else
cheapFileDets.setIdCode(null);
}
List<String> miscList = new ArrayList<>();
for (int i = 7; i < len - 1; i++) {
miscList.add(lineTokens[i]);
}
StringBuilder miscAll = new StringBuilder("");
for (String miscs : miscList) {
miscAll.append(miscs + " ");
}
cheapFileDets.setMiscAll(miscAll.toString());
cheapDataList.add(cheapFileDets);
}
System.out.println("File content" + sb.toString());
System.out.println("file date is: " + fileStartDate);
System.out.println("*************");
/*
* for (String strToks : lineTokens) { System.out.println(strToks);
* }
*/
// System.out.println(cheapDataList);
Iterator<CheapData> itrCheapData = cheapDataList.listIterator();
while (itrCheapData.hasNext()) {
System.out.println(itrCheapData.next());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
package com.msa.bean;
public class CheapData {
private String lineNum;
private String date;
private String cheapReference;
private String aircraftCode;
private String identifierCode;
private String licenseCode;
private String codeOne;
private String codeTwo;
private String codeThree;
private String idCode;
private String miscAll;
public String getLineNum() {
return lineNum;
}
public void setLineNum(String lineNum) {
this.lineNum = lineNum;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCheapReference() {
return cheapReference;
}
public void setCheapReference(String cheapReference) {
this.cheapReference = cheapReference;
}
public String getAircraftCode() {
return aircraftCode;
}
public void setAircraftCode(String aircraftCode) {
this.aircraftCode = aircraftCode;
}
public String getIdentifierCode() {
return identifierCode;
}
public void setIdentifierCode(String identifierCode) {
this.identifierCode = identifierCode;
}
public String getLicenseCode() {
return licenseCode;
}
public void setLicenseCode(String licenseCode) {
this.licenseCode = licenseCode;
}
public String getCodeOne() {
return codeOne;
}
public void setCodeOne(String lineTokens) {
this.codeOne = lineTokens;
}
public String getCodeTwo() {
return codeTwo;
}
public void setCodeTwo(String lineTokens) {
this.codeTwo = lineTokens;
}
public String getCodeThree() {
return codeThree;
}
public void setCodeThree(String codeThree) {
this.codeThree = codeThree;
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
public String getMiscAll() {
return miscAll;
}
public void setMiscAll(String miscAll) {
this.miscAll = miscAll;
}
public CheapData(String lineNum, String date, String cheapReference,
String aircraftCode, String identifierCode, String licenseCode,
String codeOne, String codeTwo, String codeThree, String idCode,
String miscAll) {
super();
this.lineNum = lineNum;
this.date = date;
this.cheapReference = cheapReference;
this.aircraftCode = aircraftCode;
this.identifierCode = identifierCode;
this.licenseCode = licenseCode;
this.codeOne = codeOne;
this.codeTwo = codeTwo;
this.codeThree = codeThree;
this.idCode = idCode;
this.miscAll = miscAll;
}
#Override
public String toString() {
return "CheapData [lineNum=" + lineNum + ", date=" + date
+ ", cheapReference=" + cheapReference + ", aircraftCode="
+ aircraftCode + ", identifierCode=" + identifierCode
+ ", licenseCode=" + licenseCode + ", codeOne=" + codeOne
+ ", codeTwo=" + codeTwo + ", codeThree=" + codeThree
+ ", idCode=" + idCode + ", miscAll=" + miscAll + "]";
}
public CheapData() {
super();
}
}
Please can anyone help me out in this regard. I want to parse above file and populate each columns from that to an object using setters in java.
Please do suggest me how to achieve this and kindly let me know if my query not clear.

Tomcat not logging to file

Hi wrote my own little Logger class to write log output into files, the class looks like this:
public class Logger {
private String prefix;
private String pathToLogFiles = "/tmp/sos/logs/";
private String infoLog;
private String errorLog;
private boolean doLogtoFile;
public Logger(String prefix, Class classname, boolean logToFile) {
this.prefix = "[" + prefix + "]";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
this.infoLog = this.pathToLogFiles + "info_" + sdf.format(now) + ".log";
this.errorLog = this.pathToLogFiles + "error_" + sdf.format(now) + ".log";
this.doLogtoFile = logToFile;
System.out.println("Will log to: " + this.infoLog + " and " + this.errorLog);
}
public void info(String message) {
String logmessage = prefix + " INFO " + message;
if( this.doLogtoFile ) {
try {
Files.write(Paths.get(infoLog), logmessage.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.out.println(prefix + message);
}
} else {
System.out.println(prefix + message);
}
}
public void error(String message) {
String logmessage = prefix + " ERROR " + message;
if( this.doLogtoFile ) {
try {
Files.write(Paths.get(errorLog), logmessage.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.out.println(prefix + message);
}
} else {
System.out.println(prefix + message);
}
}
}
Permissions of the directory and subdirectories are all set up correctly and owned by the tomcat user. However I don't receive any logoutput, nor are the log files even created.
Could anyone see what could be going wrong?
Strangely enough I am not getting any Exception
Many thanks for any help

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