I have a class which represents an ArrayList stored in a file, because I need an ArrayList with multiple gigabytes of data in it which is obviously too large to be stored in memory. The data is represented by a class called Field and the function Field.parse() is just for converting the Field into a String and the other way.
The Field class stores a list of (strange) chess pieces and their coordinates.
My class is working fine, but it takes a long time to add an element to the file and I need my program to run as fast as possible. Does anyone know a more efficient/faster way of doing things?
Also, I am not allowed to use external libraries/apis. Please keep that in mind.
This is the class which is responsible for storing Field objects in a temp file:
private File file;
private BufferedReader reader;
private BufferedWriter writer;
public FieldSaver() {
try {
file = File.createTempFile("chess-moves-", ".temp");
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
public void add(Field field) {
try {
File temp = File.createTempFile("chess-moves-", ".temp");
writer = new BufferedWriter(new FileWriter(temp));
reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.write(field.parse());
writer.close();
file.delete();
file = new File(temp.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
public Field get(int n) {
try {
reader = new BufferedReader(new FileReader(file));
for (int i = 0; i < n; i++) {
reader.readLine();
}
String line = reader.readLine();
reader.close();
return Field.parse(line);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And this is the Field class:
private WildBoar wildBoar;
private HuntingDog[] huntingDogs;
private Hunter hunter;
private int size;
#Override
public String toString() {
String result = "Wildschwein: " + wildBoar.toString();
for (HuntingDog dog : huntingDogs) {
result += "; Hund: " + dog.toString();
}
return result + "; Jäger: " + hunter.toString();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Field) {
Field field = (Field) obj;
HuntingDog[] dogs = field.getHuntingDogs();
return wildBoar.equals(field.getWildBoar()) && hunter.equals(field.getHunter()) && huntingDogs[0].equals(dogs[0]) && huntingDogs[1].equals(dogs[1]) && huntingDogs[2].equals(dogs[2]);
}
return false;
}
public Field(int size, WildBoar wildBoar, HuntingDog[] huntingDogs, Hunter hunter) {
this.size = size;
this.wildBoar = wildBoar;
this.huntingDogs = huntingDogs;
this.hunter = hunter;
}
public WildBoar getWildBoar() {
return wildBoar;
}
public HuntingDog[] getHuntingDogs() {
return huntingDogs;
}
public Hunter getHunter() {
return hunter;
}
public int getSize() {
return size;
}
public static Field parse(String s) {
String[] arr = s.split(",");
WildBoar boar = WildBoar.parse(arr[0]);
Hunter hunter = Hunter.parse(arr[1]);
HuntingDog[] dogs = new HuntingDog[arr.length - 2];
for(int i = 2; i < arr.length; i++) {
dogs[i - 2] = HuntingDog.parse(arr[i]);
}
return new Field(8, boar, dogs, hunter);
}
public String parse() {
String result = wildBoar.parse() + "," + hunter.parse();
for(HuntingDog dog : huntingDogs) {
result += "," + dog.parse();
}
return result;
}
Here's an MCVE to do what you want, based on the information you provided.
You can run it and see that it can save a Field to the file and get a Field by index very quickly.
The Fields are constant length, so you can get a Field by index by going to byte offset of index times field length in bytes. This would be significantly more difficult if the field were not constant length.
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FieldSaver implements Closeable {
public static void main(String[] args) throws IOException {
File f = File.createTempFile("chess-moves-", ".temp");
try (FieldSaver test = new FieldSaver(f);) {
for (byte i = 0; i < 100; i++) {
test.add(new Field(8, new WildBoar(i, i), new Hunter(i, i), new HuntingDog[] {
new HuntingDog(i, i),
new HuntingDog(i, i),
new HuntingDog(i, i) }));
}
// Get a few Fields by index
System.out.println(test.get(0));
System.out.println(test.get(50));
System.out.println(test.get(99));
// EOF exception, there is no Field 100
// System.out.println(test.get(100));
}
}
private final RandomAccessFile data;
public FieldSaver(File f) throws FileNotFoundException {
data = new RandomAccessFile(f, "rw");
}
public void add(Field field) throws IOException {
data.seek(data.length());
field.write(data);
}
public Field get(int index) throws IOException {
data.seek(index * Field.STORAGE_LENGTH_BYTES);
return Field.read(data);
}
public void close() throws IOException { data.close(); }
static abstract class Piece {
protected byte xPos;
protected byte yPos;
public Piece(DataInput data) throws IOException {
xPos = data.readByte();
yPos = data.readByte();
}
public Piece(byte xPos, byte yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
public void write(DataOutput data) throws IOException {
data.writeByte(xPos);
data.writeByte(yPos);
}
public String toString() { return "[" + xPos + ", " + yPos + "]"; }
}
static class Hunter extends Piece {
public Hunter(byte xPos, byte yPos) { super(xPos, yPos); }
public Hunter(DataInput data) throws IOException { super(data); }
}
static class HuntingDog extends Piece {
public HuntingDog(byte xPos, byte yPos) { super(xPos, yPos); }
public HuntingDog(DataInput data) throws IOException { super(data); }
}
static class WildBoar extends Piece {
public WildBoar(byte xPos, byte yPos) { super(xPos, yPos); }
public WildBoar(DataInput data) throws IOException { super(data); }
}
static class Field {
// size of boar + hunter + 3 dogs
public static final int STORAGE_LENGTH_BYTES = 2 + 2 + (3 * 2);
private int size;
private WildBoar boar;
private Hunter hunter;
private final HuntingDog[] dogs;
public Field(int size, WildBoar wildBoar, Hunter hunter, HuntingDog[] huntingDogs) {
this.size = size;
this.boar = wildBoar;
this.hunter = hunter;
this.dogs = huntingDogs;
}
public String toString() {
String result = "Wildschwein: " + boar.toString();
for (HuntingDog dog : dogs) {
result += "; Hund: " + dog.toString();
}
return result + "; Jäger: " + hunter.toString();
}
public static Field read(DataInput data) throws IOException {
WildBoar boar = new WildBoar(data);
Hunter hunter = new Hunter(data);
HuntingDog[] dogs = new HuntingDog[3];
for (int i = 0; i < 3; i++) {
dogs[i] = new HuntingDog(data);
}
return new Field(8, boar, hunter, dogs);
}
public void write(DataOutput data) throws IOException {
boar.write(data);
hunter.write(data);
for (HuntingDog dog : dogs) {
dog.write(data);
}
}
}
}
Use a Map implementation like Cache from ehcache. This library will optimize for you so you don't have to handle writing and reading to disk and manage when to keep it in memory or on disk. You can just use it as a normal map. You probably want a map instead of a list for faster lookup so the library can optimize even more for you.
http://www.ehcache.org/
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.heap(100))
.build())
.build(true);
Cache<Long, String> preConfigured
= cacheManager.getCache("preConfigured", Long.class, String.class);
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
I am trying to implement a save and load function in my program that saves an arrayList to a textfile and then can later load all of the past lists I have saved and print them out. I am currently using these two methods:
public static void save(Serializable data, String fileName) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream((Files.newOutputStream(Paths.get(fileName))))) {
oos.writeObject(data);
}
}
public static Object load(String fileName) throws Exception {
try (ObjectInputStream oos = new ObjectInputStream((Files.newInputStream(Paths.get(fileName))))) {
return oos.readObject();
}
}
As well as a class that represents a list as serializable data.
The problem with this is that it won't save the data after I terminate the program, and when it loads data it prints it with a great deal of extra text besides the list I want it to return. Is there a better or easier way of doing this?
I once had a same problem. So I will show you how to do it ...
Be the below Level class is what is to be saved:
public class Level implements Serializable {
private int level = 1;
private int star;
private int point;
// Constructor
public Level() {
}
public void setLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
public void setStar(int stars) {
this.star = stars;
}
public int getStar() {
return star;
}
public void setPoint(int points) {
this.point = points;
}
public int getPoint() {
return point;
}
#Override
public String toString() {
return "Level-" + level + " " +
(star > 1 ? star + " stars": star + " star") + " " +
(point > 1 ? point + " points" : point + " point") + "\n";
}
}
We will save the list into this file:
private static final String FILENAME = "data.level";
This is the List of our objects:
List<Level> mLevels;
Call this method to save the list into the file:
private void save() {
if(mLevels.isEmpty()) {
return;
}
try
{
ObjectOutputStream oos = new ObjectOutputStream(mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE));
oos.writeObject(mLevels);
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Use this method to load the list from saved file. Notice, we cast the list of our object with this (List<Level>) ois.readObject(); in the method:
private void load() {
try
{
ObjectInputStream ois = new ObjectInputStream(mContext.openFileInput(FILENAME));
mLevels = (List<Level>) ois.readObject();
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
catch (ClassNotFoundException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(mLevels == null) {
mLevels = new ArrayList<>();
//Toast.makeText(mContext,"List created",Toast.LENGTH_SHORT).show();
}
}
By now, you should get the idea of how to save your own list.
As it stands I have a data set in the form of a .csv file which you can find here. Also there is some brief documentation on it which you can find here. What I am attempting to do is to manipulate the data set so that I can work with some machine learning algorithms but as it stands I can't seem to print the outputted data to the console
ImageMatrix.java
import java.util.Arrays;
public class ImageMatrix {
public static int[] data;
public int classCode;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
}
public String toString() {
return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
}
ImageMatrixDB.java
import java.io.*;
import java.util.*;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public static ImageMatrixDB load(String f) throws IOException {
ImageMatrixDB result = new ImageMatrixDB();
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
for (String line; null != (line = br.readLine()); ) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
result.list.add(new ImageMatrix(data, classCode));
}
System.out.println(ImageMatrix.data.toString());
}
return result;
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
i.load("dataset1.csv"); // <<< ERROR IS HERE
}
}
The error is within my main function on the line i.load(... I know I must be missing something or have made a mistake somewhere, I have tried altering the data from static but it just throws more errors and I can't figure it out. Any ideas?
Your issue is in the ImageMatrix class.
You never set the int[] data in the constructor. You have:
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
}
You need:
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
this.data = data;
this.classCode = classCode;
}
Here is your updated/complete/working code:
ImageMatrix:
import java.util.*;
public class ImageMatrix {
private int[] data;
private int classCode;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
this.data = data;
this.classCode = classCode;
}
public String toString() {
return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
}
ImageMatrixDB:
import java.util.*;
import java.io.*;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
private List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public ImageMatrixDB load(String f) throws IOException {
try (
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
String line = null;
while((line = br.readLine()) != null) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
ImageMatrix matrix = new ImageMatrix(data, classCode);
list.add(matrix);
}
}
return this;
}
public void printResults(){
for(ImageMatrix matrix: list){
System.out.println(matrix);
}
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
try{
i.load("cw2DataSet1.csv");
i.printResults();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
Your load method can throw an IOException. You need to catch it in order to successfully compile
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
try{
i.load("dataset1.csv"); // <<< ERROR IS HERE
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Well, I'm making a game and in my framework I created a save system. My save system works fine but for some reason, it does not seem to want to save my files! It gives me this error:
Chaos Blades: There was an error in creating the file!
Exception in thread "LWJGL Application" java.lang.NullPointerException
at cb.core.FileBuilder.writeString(FileBuilder.java:31)
at cb.player.PlayerStats.init(PlayerStats.java:46)
at cb.player.Player.init(Player.java:17)
at cb.entities.EntityManager.init(EntityManager.java:8)
at cb.core.Initialiser.init(Initialiser.java:11)
at cb.core.Main.create(Main.java:11)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Here's my FileBuilder class:
package cb.core;
import java.io.*;
import java.util.*;
public class FileBuilder {
private Formatter formatter;
public void openFile(String file) {
try {
formatter = new Formatter(file);
} catch(Exception e) {
System.err.println("Chaos Blades: There was an error in creating the file!");
}
}
public void closeFile() {
formatter.close();
}
public void writeInteger(int i) {
formatter.format("%i \n", i);
}
public void writeFloat(float f) {
formatter.format("%f \n", f);
}
public void writeString(String s) {
formatter.format("%s \n", s);
}
public void appendInt(String file, int i) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(i);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendFloat(String file, float f) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(f);
} catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendString(String file, String s) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(newFileWriter(file, true)))) {
out.println(s);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
}
Here's my PlayerStats class:
package cb.player;
import java.io.*;
import cb.core.*;
import cb.core.FileReader;
public class PlayerStats {
public enum Class {
WARRIOR, ARCHER, MAGE
}
private static int health, attack, defense, melee, ranged, magic, crafting;
private static int hxp, axp, dxp, mexp, rxp, mgxp, cxp;
private static Class pclass;
static void init() {
FileBuilder saver = new FileBuilder();
FileReader reader = new FileReader();
File statfile = new File("saves/stats.cbsave");
File xpfile = new File("saves/xp.cbsave");
if(statfile.exists()) {
reader.openFile("saves/stats.cbsave");
health = reader.setVariableToIntUsingFilePosition(1);
attack = reader.setVariableToIntUsingFilePosition(2);
defense = reader.setVariableToIntUsingFilePosition(3);
melee = reader.setVariableToIntUsingFilePosition(4);
ranged = reader.setVariableToIntUsingFilePosition(5);
magic = reader.setVariableToIntUsingFilePosition(6);
crafting = reader.setVariableToIntUsingFilePosition(7);
pclass.equals(reader.setVariableToStringUsingFilePosition(8));
reader.closeFile();
} else {
health = 1;
attack = 1;
defense = 1;
melee = 1;
ranged = 1;
magic = 1;
crafting = 1;
saver.openFile("saves/stats.cbsave");
saver.writeString("" + health);
saver.writeString("" + attack);
saver.writeString("" + defense);
saver.writeString("" + melee);
saver.writeString("" + ranged);
saver.writeString("" + magic);
saver.writeString("" + crafting);
saver.writeString(pclass.toString());
saver.closeFile();
}
if(xpfile.exists()) {
reader.openFile("saves/xp.cbsave");
hxp = reader.setVariableToIntUsingFilePosition(1);
axp = reader.setVariableToIntUsingFilePosition(2);
dxp = reader.setVariableToIntUsingFilePosition(3);
mexp = reader.setVariableToIntUsingFilePosition(4);
rxp = reader.setVariableToIntUsingFilePosition(5);
mgxp = reader.setVariableToIntUsingFilePosition(6);
cxp = reader.setVariableToIntUsingFilePosition(7);
reader.closeFile();
} else {
hxp = 0;
axp = 0;
dxp = 0;
mexp = 0;
rxp = 0;
mgxp = 0;
cxp = 0;
saver.openFile("saves/xp.cbsave");
saver.writeInteger(hxp);
saver.writeInteger(axp);
saver.writeInteger(dxp);
saver.writeInteger(mexp);
saver.writeInteger(rxp);
saver.writeInteger(mgxp);
saver.writeInteger(cxp);
saver.closeFile();
}
}
static void dispose() {
FileBuilder saver = new FileBuilder();
saver.openFile("saves/stats.cbsave");
saver.writeInteger(health);
saver.writeInteger(attack);
saver.writeInteger(defense);
saver.writeInteger(melee);
saver.writeInteger(ranged);
saver.writeInteger(magic);
saver.writeInteger(crafting);
saver.writeString(pclass.toString());
saver.closeFile();
saver.openFile("saves/xp.cbsave");
saver.writeInteger(hxp);
saver.writeInteger(axp);
saver.writeInteger(dxp);
saver.writeInteger(mexp);
saver.writeInteger(rxp);
saver.writeInteger(mgxp);
saver.writeInteger(cxp);
saver.closeFile();
}
public static int getHealth() {
return health;
}
public static int getAttack() {
return attack;
}
public static int getDefense() {
return defense;
}
public static int getMelee() {
return melee;
}
public static int getRanged() {
return ranged;
}
public static int getMagic() {
return magic;
}
public static int getCrafting() {
return crafting;
}
public static int getHealthXP() {
return hxp;
}
public static int getAttackXP() {
return hxp;
}
public static int getDefenseXP() {
return hxp;
}
public static int getMeleeXP() {
return hxp;
}
public static int getRangedXP() {
return hxp;
}
public static int getMagicXP() {
return hxp;
}
public static int getCraftingXP() {
return hxp;
}
public static void setHealth(int health) {
PlayerStats.health = health;
}
public static void setAttack(int attack) {
PlayerStats.attack = attack;
}
public static void setDefense(int defense) {
PlayerStats.defense = defense;
}
public static void setMelee(int melee) {
PlayerStats.melee = melee;
}
public static void setRanged(int ranged) {
PlayerStats.ranged = ranged;
}
public static void setMagic(int magic) {
PlayerStats.magic = magic;
}
public static void setCrafting(int crafting) {
PlayerStats.crafting = crafting;
}
}
I'm not sure what's wrong so help me out please!
openFile() is failing since the file does not exist or you can't write to it. Try explicitly creating the files if they do not exist:
File statfile = new File("saves/stats.cbsave");
if(statfile.exists()) {
...
} else {
statfile.createNewFile();
...
}
I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}