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.
Related
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();
}
I have a 'Person' class where i stored data like name, surname etc. I make 5 object type Person, add them to ArrayList, and save this ArrayList to file. Next i'm loading from this file ArrayList and i have 5 person. Problem is when i want save again for example 10 object Person. When i'm loading ArrayList from file i'm getting only 5 person from first writing. If i repeat this still i will have load data from first writing to this file. How i can fix this ?
public class Data {
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons(5);
Data.loadPersons();
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
System.out.println("\n-----------\nNext Round\n-----------\n");
Data.savePersons(10);
Data.loadPersons();
}
/** Save a couple of Person Object to file C:/data.ser */
public static void savePersons(int noOfPersonToSave) throws IOException {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object and add them to ArrayList 'persons' for example */
for (int i = 0; i < noOfPersonToSave; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890" +i);
persons.add(personTest);
}
try {
fout = new FileOutputStream("C:\\data.ser", 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: " + ex.getMessage());
} finally {
if (oos != null) {
oos.close();
}
}
}
/** Load previously saved a couple of Person Object in file C:/data.ser */
public static void loadPersons() throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("C:\\data.ser");
ois = new ObjectInputStream(fis);
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");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
} finally {
if (ois != null) {
ois.close();
}
}
}}
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;
}}
new FileOutputStream("C:\\data.ser", true)
You're passing true for the append parameter. So you're appending a list of 10 persons to the file, after the already existing list of 5 people. And since you only read one list, you read the first you wrote, which contains 5 persons.
Pass false instead of true.
I have this textfile which I like to sort based on HC from the pair HC and P3
This is my file to be sorted (avgGen.txt):
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
6805.62,HC
17933.10,P3
Then my desired output into a new textfile (output.txt) is:
6805.62,HC
17933.10,P3
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
How can I sort the pairs HC and P3 from textfile where HC always appear for odd numbered index and P3 appear for even numbered index but I want the sorting to be ascending based on the HC value?
This is my code:
public class SortTest {
public static void main (String[] args) throws IOException{
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}
Collections.sort(rows);
for (Double toStr : rows){
convertString.add(String.valueOf(toStr));
}
FileWriter writer = new FileWriter("output.txt");
for(String cur: convertString)
writer.write(cur +"\n");
reader.close();
writer.close();
}
}
Please help.
When you read from the input file, you essentially discarded the string values. You need to retain those string values and associate them with their corresponding double values for your purpose.
You can
wrap the double value and the string value into a class,
create the list using that class instead of the double value alone
Then sort the list based on the double value of the class using either a Comparator or make the class implement Comparable interface.
Print out both the double value and its associated string value, which are encapsulated within a class
Below is an example:
static class Item {
String str;
Double value;
public Item(String str, Double value) {
this.str = str;
this.value = value;
}
}
public static void main (String[] args) throws IOException {
ArrayList<Item> rows = new ArrayList<Item>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(new Item(data[1], avg));
}
Collections.sort(rows, new Comparator<Item>() {
public int compare(Item o1, Item o2) {
if (o1.value < o2.value) {
return -1;
} else if (o1.value > o2.value) {
return 1;
}
return 0;
}
});
FileWriter writer = new FileWriter("output.txt");
for(Item cur: rows)
writer.write(cur.value + "," + cur.str + "\n");
reader.close();
writer.close();
}
When your program reads lines from the input file, it splits each line, stores the double portion, and discards the rest. This is because only data[0] is used, while data[1] is not part of any expression.
There are several ways of fixing this. One is to create an array of objects that have the double value and the whole string:
class StringWithSortKey {
public final double key;
public final String str;
public StringWithSortKey(String s) {
String[] data = s.split(",");
key = Double.parseDouble(data[0]);
str = s;
}
}
Create a list of objects of this class, sort them using a custom comparator or by implementing Comparable<StringWithSortKey> interface, and write out str members of sorted objects into the output file.
Define a Pojo or bean representing an well defined/organized/structured data type in the file:
class Pojo implements Comparable<Pojo> {
private double value;
private String name;
#Override
public String toString() {
return "Pojo [value=" + value + ", name=" + name + "]";
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* #param value
* #param name
*/
public Pojo(double value, String name) {
this.value = value;
this.name = name;
}
#Override
public int compareTo(Pojo o) {
return ((Double) this.value).compareTo(o.value);
}
}
then after that: read->sort->store:
public static void main(String[] args) throws IOException {
List<Pojo> pojoList = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader("chat.txt"));
String s;
String[] data;
while ((s = reader.readLine()) != null) {
data = s.split(",");
pojoList.add(new Pojo(Double.parseDouble(data[0]), data[1]));
}
Collections.sort(pojoList);
FileWriter writer = new FileWriter("output.txt");
for (Pojo cur : pojoList)
writer.write(cur.toString() + "\n");
reader.close();
writer.close();
}
Using java-8, there is an easy way of performing this.
public static void main(String[] args) throws IOException {
List<String> lines =
Files.lines(Paths.get("D:\\avgGen.txt"))
.sorted((a, b) -> Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.')))))
.collect(Collectors.toList());
Files.write(Paths.get("D:\\newFile.txt"), lines);
}
Even better, using a Method reference
public static void main(String[] args) throws IOException {
Files.write(Paths.get("D:\\newFile.txt"),
Files.lines(Paths.get("D:\\avgGen.txt"))
.sorted(Test::compareTheStrings)
.collect(Collectors.toList()));
}
public static int compareTheStrings(String a, String b) {
return Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.'))));
}
By using double loop sort the items
then just comapre it using the loop and right in the sorted order
public static void main(String[] args) throws IOException {
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:/Temp/AvgGen.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s;
try {
while((s = reader.readLine())!=null){
String[] data = s.split(",");
convertString.add(s);
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileWriter writer = new FileWriter("C:/Temp/output.txt");;
Collections.sort(rows);
for (double sorted : rows) {
for (String value : convertString) {
if(Double.parseDouble(value.split(",")[0])==sorted)
{
writer.write(value +"\n");
}
}
}
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
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.