Write and Read a Vector to a serialized file in Java? - java

I am trying a vector to a serialized file. The vector is made of a class I created. Below is the class.
public class Product implements java.io.Serializable{
public String description;
public String code;
public double price;
public String unit;
public Product(String w, String x, double y, String z){ //Constructor for Product
description = w;
code = x;
price = y;
unit = z;
}
}
I created a vector:
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"));
Vector <Product> products=new Vector();//declare a vector of products
for(int i=0;i<101;i++){//enter the values for the class
System.out.print("Description: ");
String w = in.readLine();
char f = w.charAt(0);
if(f=='#'){//Statement to break out of the loop when the user enters #
System.out.println();
break;
}else{//Code to read input from user
System.out.print("Code: ");
String x = in.readLine().toUpperCase();
boolean finished=false;
while(!finished){
System.out.print("Price: ");
String a =in.readLine();
try{//try catch statement
double y= Double.parseDouble(a);
System.out.print("Unit: ");
String z = in.readLine();
Product temp = new Product(w, x, y, z);
products.insertElementAt(temp, i);//values are assigned to
//the vector elements
System.out.println();
finished=true;
}
catch(Exception e){
System.out.println("do not enter letters for the price");
}
}
}
}
So I have a vector of Product. What I need to know is how to write it to into a serialized file, file.ser, then how to read from that file back into a vector of Product. I have been experimenting with this for a whole day and can't seem to get anything right or find anything useful on the internet.

I added a toString() method do class Product to get proper debug output:
public class Product implements Serializable {
// ....
#Override
public String toString() {
return description + "/" + code + "/" + price + "/" + unit;
}
}
You can put the whole vector instance to the ObjectOutputStream.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
public class Main {
private static final String FILE_NAME = "file.ser";
public static void main(String[] args) throws Exception {
final Vector<Product> products = new Vector<Product>();
products.add(new Product("1", "1", 1.0, "1"));
products.add(new Product("2", "2", 2.0, "2"));
products.add(new Product("3", "3", 3.0, "3"));
products.add(new Product("4", "4", 4.0, "4"));
System.out.println("Original products : " + products);
final ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
try {
out.writeObject(products);
} finally {
out.close();
}
final ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(FILE_NAME)));
final Vector<Product> productsFromFile = (Vector<Product>) in.readObject();
System.out.println("Products from file: " + productsFromFile);
}
}
And the output is:
Original products : [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Products from file: [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]

Try something like the following to write a serialisable object:
Product product = new Product("Apples", "APP", 1.99, 200);
try{
OutputStream file = new FileOutputStream( "output.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(product);
}
finally{
output.close();
}
}
catch(IOException ex){
System.out.println("Output failed.");
}
To read it in you read do the opposite, putting result into an object as follows:
Product product = (Product)input.readObject();
where input is an ObjectInputStream.

I think that you can use this example to write and read the file:
http://www.java-samples.com/showtutorial.php?tutorialid=392
you can search in google for: "java file reader example"
regards

I think that you forgot to add the vector to the class. In your code you assign temp to new Product, then you add the values to the vector. Vector is filled with new values, but Vector is not part of the class Product. Therefore, the data is still in Vector, but it's will never be saved via serializable. (if this is what you try to accomplish)
Here is a small example (written in Java Processing):
import java.io.*;
GameChar Elf, Troll;
void setup() {
Elf = new GameChar(50, new String[] {
"bow", "sword", "dust"
}
);
Troll = new GameChar(200, new String[] {
"bare hands", "big axe"
}
);
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(sketchPath+"/data/game.txt"));
os.writeObject(Elf);
os.writeObject(Troll);
os.close();
}
catch (Exception e) {
println(e);
}
Elf = null;
Troll = null;
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(sketchPath+"/data/game.txt"));
Elf = (GameChar) is.readObject();
Troll = (GameChar) is.readObject();
println("Elf has "+ Elf.getHealth()+" health, and fights with "+ Elf.getWeapons());
println("Troll has "+ Troll.getHealth()+" health, and fights with "+ Troll.getWeapons());
}
catch (Exception e) {
println(e);
}
}
void draw() {
}
static class GameChar implements Serializable {
int health;
String[] weapons;
GameChar(int h, String[] w) {
health = h;
weapons = w;
}
int getHealth() {
return health;
}
String getWeapons() {
String weaponList = "";
for (String weapon : weapons)
weaponList += weapon + " ";
return weaponList;
}
}

Related

Java - How to save an ArrayList into a file and open it?

I made a class called Subject. The class consists of these lines:
class Subject {
int serial;
Double credit, gpa, tgpa = 0.0;
public Subject(int serial, Double credit, Double gpa, Double tgpa) {
this.serial = serial;
this.credit = credit;
this.gpa = gpa;
this.tgpa = tgpa;
}
public int getSerial() {
return serial;
}
public void setSerial(int serial) {
this.serial = serial;
}
public Double getCredit() {
return credit;
}
public void setCredit(Double credit) {
this.credit = credit;
}
public Double getGpa() {
return gpa;
}
public void setGpa(Double gpa) {
this.gpa = gpa;
}
public Double getTgpa() {
return tgpa;
}
public void setTgpa(Double tgpa) {
this.tgpa = tgpa;
}
}
I'm trying to create two methods for Saving the ArrayList of Subject into a file and Reopen it as an ArrayList of Subject.
Any solution?
You could use serialization and deserialization to write it into a file:
try (FileOutputStream fos = new FileOutputStream("serializedObject.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(yourArrayList);
}
Then you can read it again and cast it:
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("serializedObject.txt"));
//Gets the object
ois.readObject();
A small example from:Java serialization
A very small note with these examples: I kept the original example.
Please always close your files and streams in the finally clause!
Create object:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Write object to file:
import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i) {
i.printStackTrace();
}
}
}
To get the list back:
import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i) {
i.printStackTrace();
return;
}catch(ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
You can either use Java Serialization and Deserialization or Jackson API to store and retrieve .

Operating on a file in java

I'm having a bit of a problem with all the FileReaders and FileWriters in java. I want my program to get the name of the person and then after asking them a couple of questions evaluate their score. That is pretty easy but now what I want to do is to document it in a log file like this:
Jacob : 10
Mark : 15
Steve : 7
And then every time any of these people open the program it will retrieve their current score or if it is someone new it would append their name and score.
I can't find a way to search a file and then retrieve the integer at the end.
EDIT:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Main {
static Scores scoreClass = new Scores();
private static void setupMap() {
try {
FileInputStream fin = new FileInputStream("scores.map");
#SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fin);
scoreClass = (Scores) ois.readObject();
} catch (Exception e) {
System.err.println("Could not load score data");
e.printStackTrace();
}
}
private static void saveMap() {
try {
FileOutputStream fout = new FileOutputStream("scores.map");
#SuppressWarnings("resource")
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(scoreClass);
} catch (Exception e) {
System.err.println("Could not save score data");
e.printStackTrace();
}
}
public static void main(String[] args) {
setupMap();
int score = 0;
String guess;
String[][] questions_with_answers = {{"I __________ to school.(go)", "She __________ tennis. (play)", "She _______ a bitch. (be)"}, {"am going", "was playing", "is being"}};
Scanner answer = new Scanner(System.in);
Scanner studentInput = new Scanner(System.in);
System.out.println("What is your name?");
String name = answer.nextLine();
if(Scores.getScore(name) == -1){
Scores.setScore(name, score);
} else {
Scores.getScore(name);
}
System.out.println("Hello " + name + ". Your score is: " + score);
for(int i = 0; i < (questions_with_answers[0].length); i++){
System.out.println(questions_with_answers[0][i]);
guess = studentInput.nextLine();
if(guess.equals(questions_with_answers[1][i])){
System.out.println("Correct! You get 1 point.");
score = score + 1;
System.out.println("Your score is " + score);
} else {
System.out.println("You made a mistake! No points...");
}
}
System.out.printf("Congrats! You finished the test with "+ score +" points out of " + questions_with_answers[0].length);
Scores.setScore(name, score);
saveMap();
answer.close();
studentInput.close();
}
}
This doesn't throw any exceptions but still doesn't read the input from the file :/
You could store the data as a hash map and then serialize it to a save file
I wrote an example that includes a class called Scores which has methods to read a score and add a score to a contained hash map. I also added methods in the main class for saving and opening a file that will contain the score class data.
Main Class:
public class Main {
static Scores scoreClass = new Scores();
public static void main(String[] args) {
setupMap();
//Do score calculations
saveMap();
}
private static void setupMap() {
try {
FileInputStream fin = new FileInputStream("scores.map");
#SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fin);
scoreClass = (Scores) ois.readObject();
} catch (Exception e) {
System.err.println("Could not load score data");
e.printStackTrace();
}
}
private static void saveMap() {
try {
FileOutputStream fout = new FileOutputStream("scores.map");
#SuppressWarnings("resource")
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(scoreClass);
} catch (Exception e) {
System.err.println("Could not save score data");
e.printStackTrace();
}
}
}
Scores Class:
public class Scores implements Serializable{
private static final long serialVersionUID = 1L;
public static Map<String, Integer> scoreMap = new HashMap<String, Integer>();
public static int getScore(String name) {
if (scoreMap.containsKey(name)) {
return scoreMap.get(name);
} else {
return -1;
}
}
public static void setScore(String name, int score) {
scoreMap.put(name, score);
}
}

java.lang.RuntimeException: Cannot open files

I have DataManager.java and ExportBasicTest.java for tests.
I can't get my DataManager.java to pass the tests, even though they seem like basic errors.
I tried messing around with the directories of the two files and the file that I create called ExportedFile.txt but I can't fix any of my errors.
I have two arrayLists of type <Passenger> and <Flight> which have different parts of each. These parts are what my long methods are referencing.
DataManager.java:
import java.io.*;
import java.util.*;
public class DataManager {
private static File fileName;
private static Formatter fileFormatter;
private static ArrayList<Flight> theFlights;
private static ArrayList<Passenger> thePassengers;
public static void exportData(String filename, ArrayList<Passenger> passengers, ArrayList<Flight> flights) {
fileName = new File(filename);
theFlights = flights;
thePassengers = passengers;
openFile();
addFlights();
addPassengers();
closeFile();
}
public static void openFile(){
try{
fileFormatter = new Formatter(fileName);
System.out.println("you created a file");
}
catch(Exception e){
System.out.println("You have an error.");
}
}
public static int AlertsCount(int i){
return thePassengers.get(i).getAlerts().size();
}//AlertsCount
public static String listAlerts(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getAlerts().size();z++){
stringBuilder.append(thePassengers.get(i).getAlerts().get(z) + System.getProperty("line.separator"));
}
String alerts = stringBuilder.toString();
return alerts;
}//listAlerts close
public static int BookedFlightsCount(int i){
return thePassengers.get(i).getBookedFlights().size();
}//bookedFlightsCount close
public static String listBookedFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getBookedFlights().size();z++){
stringBuilder.append(thePassengers.get(i).getBookedFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getBookedFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getLandingTime()) + System.getProperty("line.separator"));
}
String bookedFlights = stringBuilder.toString();
return bookedFlights;
}//listBookedFlights close
public static int StandbyFlightsCount(int i){
return thePassengers.get(i).getStandbyFlights().size();
}//StandbyFlightsCount close
public static String listStandbyFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getStandbyFlights().size();z++){
stringBuilder.append(System.getProperty("line.separator") + thePassengers.get(i).getStandbyFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getStandbyFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getLandingTime()));
}
String standbyFlights = stringBuilder.toString();
return standbyFlights;
}//listStandbyFlights close
public static void addPassengers(){
fileFormatter.format("%s%d", "#passCount ", thePassengers.size());
for(int i = 0; i<thePassengers.size();i++){
fileFormatter.format("%s%s%s%s%s%s%d%s%s%d%s%s%d%s",System.getProperty("line.separator"), "#newPass",System.getProperty("line.separator"), thePassengers.get(i).getFirstName()+" , ", thePassengers.get(i).getLastName(),System.getProperty("line.separator"),
AlertsCount(i),System.getProperty("line.separator"), listAlerts(i), BookedFlightsCount(i),System.getProperty("line.separator"), listBookedFlights(i), StandbyFlightsCount(i), listStandbyFlights(i));
}
}//addPassengers close
public static void addFlights(){
fileFormatter.format("%s%d%s", "#flightCount ", theFlights.size(), System.getProperty("line.separator"));
for(int i = 0;i<theFlights.size();i++){
fileFormatter.format("%s%s%s , %s , %d , %d%s%d%s", "#newFlight",System.getProperty("line.separator"), theFlights.get(i).getSourceAirport(), theFlights.get(i).getDestinationAirport(),
theFlights.get(i).getTakeOffTime(), theFlights.get(i).getLandingTime(), System.getProperty("line.separator"),theFlights.get(i).getCapacity(),System.getProperty("line.separator"));
}
}//addFlights close
public static void closeFile(){
fileFormatter.close();
}//closeFile close
//This function creates and writes data for a new file using the specifications ,
//given earlier in order to store the data represented by those objects stored within the two ArrayLists.
}
ExportBasicTest.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import junit.framework.Assert;
import org.junit.Test;
public class ExportBasicTest {
#Test(timeout = 1000)
public void exportExampleFile()
{
ArrayList<Flight> flightList = new ArrayList<Flight>();
Flight f1 = new Flight("MCO", "MIA", 800, 930, 8);
Flight f2 = new Flight("MIA", "ATL", 1100, 1400, 23);
Flight f3 = new Flight("ATL", "GNV", 1430, 1615, 15);
flightList.add(f1);
flightList.add(f2);
flightList.add(f3);
ArrayList<Passenger> passList = new ArrayList<Passenger>();
Passenger p1 = new Passenger("Joshua", "Horton");
Passenger p2 = new Passenger("Adam", "Smith");
passList.add(p1);
passList.add(p2);
p1.addAlert("The 7:30 flight from BTR to GNV has been cancelled!");
p1.bookFlight(f1);
p1.bookFlight(f2);
p2.bookFlight(f3);
p2.addStandbyFlight(f1);
p2.addStandbyFlight(f2);
DataManager.exportData("ExportedFile.txt", passList, flightList);
// This file, given the initial setup, should almost perfectly match the provided example file.
Assert.assertEquals("File contents are not as expected!", true, matchFiles("ProjStage3BasicFile.txt", "ExportedFile.txt"));
}
// Checks if the files match by directly comparing their exact contents.
private boolean matchFiles(String expected, String actual)
{
Scanner inFile1;
Scanner inFile2;
try
{
inFile1 = new Scanner(new File(expected));
inFile2 = new Scanner(new File(actual));
}
catch(IOException e)
{
throw new RuntimeException("Cannot open files!", e);
}
ArrayList<String> expectedLines = new ArrayList<String>();
ArrayList<String> actualLines = new ArrayList<String>();
while(inFile1.hasNextLine())
{
expectedLines.add(inFile1.nextLine());
}
while(inFile2.hasNextLine())
{
actualLines.add(inFile2.nextLine());
}
// Erase a trailing blank line at the file's end; I don't mind that.
if(actualLines.get(actualLines.size() - 1).trim().equals(""))
{
actualLines.remove(actualLines.size() - 1);
}
return expectedLines.equals(actualLines);
}
}
You need to pass the path to the files not just the names where ever you use a filename.
Your match files method is throwing an error because it cannot open the file names you passed. To use the current working directory use ./ as in "./filename.txt" as opposed to "filename.txt"
You can always check if a path exists Using java.nio.file.Files
if(Files.exists(path)){...}

Adding highscores to java game - From console to JPanel - Saving highscore in encrypted text file

I am new to Java, and learning new things everyday. English is not my mother language, I'm sorry.
So, I'm making a maze game in Java to learn while writing code.
For my maze game, the player needs to get to the exit of the maze asap. And the time he has, needs to be saved in an encrypted text file.
So I've got a package Highscores combining several classes. The code works more or less, it outputs in the console. Now what I need is that that output gets outputted on a JPanel next to my maze. I've added some extra info in the code
Here is my highscore class:
public class Highscore {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList<Score> scores;
// The name of the file where the highscores will be saved
private static final String highscorefile = "Resources/scores.dat";
//Initialising an in and outputStream for working with the file
ObjectOutputStream output = null;
ObjectInputStream input = null;
public Highscore() {
//initialising the scores-arraylist
scores = new ArrayList<Score>();
}
public ArrayList<Score> getScores() {
loadScoreFile();
sort();
return scores;
}
private void sort() {
ScoreVergelijken comparator = new ScoreVergelijken();
Collections.sort(scores, comparator);
}
public void addScore(String name, int score) {
loadScoreFile();
scores.add(new Score(name, score));
updateScoreFile();
}
public void loadScoreFile() {
try {
input = new ObjectInputStream(new FileInputStream(highscorefile));
scores = (ArrayList<Score>) input.readObject();
} catch (FileNotFoundException e) {
System.out.println("[Laad] FNF Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("[Laad] CNF Error: " + e.getMessage());
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
}
}
}
public void updateScoreFile() {
try {
output = new ObjectOutputStream(new FileOutputStream(highscorefile));
output.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file");
} catch (IOException e) {
System.out.println("[Update] IO Error: " + e.getMessage());
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException e) {
System.out.println("[Update] Error: " + e.getMessage());
}
}
}
public String getHighscoreString() {
String highscoreString = "";
int max = 10;
ArrayList<Score> scores;
scores = getScores();
int i = 0;
int x = scores.size();
if (x > max) {
x = max;
}
while (i < x) {
highscoreString += (i + 1) + ".\t" + scores.get(i).getNaam() + "\t\t" + scores.get(i).getScore() + "\n";
i++;
}
return highscoreString;
}
}
Here is my Main class:
public class Main {
public static void main(String[] args) {
Highscore hm = new Highscore();
hm.addScore("Bart",240);
hm.addScore("Marge",300);
hm.addScore("Maggie",220);
hm.addScore("Homer",100);
hm.addScore("Lisa",270);
hm.addScore(LabyrinthProject.View.MainMenu.username,290);
System.out.print(hm.getHighscoreString());
} }
Score class :
public class Score implements Serializable {
private int score;
private String naam;
public Score() {
}
public int getScore() {
return score;
}
public String getNaam() {
return naam;
}
public Score(String naam, int score) {
this.score = score;
this.naam = naam;
}
}
ScoreVergelijken class (which means CompareScore)
public class ScoreVergelijken implements Comparator<Score> {
public int compare(Score score1, Score score2) {
int sc1 = score1.getScore();
int sc2 = score2.getScore();
if (sc1 > sc2){
return -1; // -1 means first score is bigger then second score
}else if (sc1 < sc2){
return +1; // +1 means that score is lower
}else{
return 0; // 0 means score is equal
}
} }
If anyone could explain to me what to use, it would be greatly appreciated! Thank you very much!
Also, how to use those highscores and store them encrypted in a text file. How can I achieve that?
Sincerely, A beginner java student.
to keep your data encrypted in a file, you can use CipherIn/OutputStream, just like this
public static void main(String[] args) throws Exception {
// got this example from http://www.java2s.com/Tutorial/Java/0490__Security/UsingCipherInputStream.htm
write();
read();
}
public static void write() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(new SecureRandom());
SecretKey key = kg.generateKey();
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
oos.writeObject(ks.getKey());
Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
pw.println("Stand and unfold yourself");
pw.flush();
pw.close();
oos.writeObject(c.getIV());
oos.close();
}
public static void read() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyfile"));
DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey key = skf.generateSecret(ks);
Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
CipherInputStream cis = new CipherInputStream(new FileInputStream("ciphertext"), c);
BufferedReader br = new BufferedReader(new InputStreamReader(cis));
System.out.println(br.readLine());
}
Basically you asked two questions and Leo answered your second question.
Your first question is...
what I need is that ...[the high scores]... gets outputted on a JPanel next to my maze
You didn't post any GUI code, but a subclass of JTextComponent would be more appropriate than a JPanel. Simply add a component, for example JTextArea and call its setText() method with your high score string as the method argument.

Sorting lines in a file by 2 fields with JAVA

I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}

Categories

Resources