So, i'm trying to save my player data onto a txt file, then load the data from the text from when the game is opened again, but its not working, I get it to save while in the game, but when I close the game, and open it back up its no longer saved, and it has all the default data in the game, and in the file...
Here is the some of the code from the game (Sorry it's in pastebin, I thought i might be too long to just paste it into here.)
Game.java
Save.java
I am in need of some assistance, trying to get it to load from the text document, and when the game opens, not resetting the text document into its default settings.
The issue is in Save.savePlayer()
At the beginning you declare saveInfo to hold the values that the game holds at that point in time. When initially loading they will hold the default values.
int[] saveInfo = { Game.hp, Game.level, Game.mana, Game.expTotal,
Game.goldTotal, Game.arrow, Game.shuriken, Game.bomb,
Game.hpPotion, Game.mpPotion, Game.potion, Game.items };
The variables here:Game.hp=100, Save.saveInfo[0]=100
Then you set all of the game variables to saveInfo at the beginning of Save.savePlayer()
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
The variables here:Game.hp=100, Save.saveInfo[0]=100
They don't change because you just set them back to their default values.
Then you load the saved state but you don't do anything with the data. You should be setting the variables after loading here so they're set to the new saveInfo values instead of the old.
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
I think this part is the problem...
private void readPlayer(String filePath) {
File inputFile;
BufferedReader inputReader;
try {
inputFile = new File(filePath);
inputReader = new BufferedReader(new FileReader(inputFile));
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
inputReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
put these lines
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
before
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
in order to read the file before setting the game values...
If you do not mind it, then using xstream and apache fileutils is an excellent solution and less coding. I am just sharing my thoughts.
import org.apache.commons.io.FileUtils;
import com.thoughtworks.xstream.XStream;
//saving your data
XStream xstream=new XStream(new DOMDriver());
String xml = xstream.toXML(yourGambeObj);
FileUtils.writeStringToFile(new File("yourfilename", xml);
//reading your data
Game gameData=xstream.fromXML(new File("yourfilename"),Game.class);
//now you can use access your methods n attribute. no conversion as you did in serialization.
Please download and add these jars.XStream &
Apache Commons IO
So, I was fiddling around with some things, and I did it! So, the problem was, that i would load it from the save data, then write over it, then load it again, for some reason, it would do the whole Save.java 2 times and just save over it, but I put them all as public static voids and instead of calling the whole Constructor, I call them by individual methods by where and what they need to do, which seem to work great! Thank you all for all your help, it helped a lot!
Related
I use XHTMLConverter to convert .docx to html, to make preview of the document. Is there any way to convert only few pages from original document? I'll be grateful for any help.
You have to parse the complete .docx file. It is not possible to read just parts of it. Otherwise if you want to know how to select a specific page number, im afraid to tell you(at least I believe) that word does not store page numbers therefore there is no function in the libary to accsess a specified page..
(I've read this at another forum, it actually might be false information).
PS: the Excel POI contains a .getSheetAt()method (this might helps you for your research)
But there are also other ways to accsess your pages. For instance you could read the lines of your docx document and search for the pagenumbers(might crash if your text contains those numbers though). Another way would be to search for the header of the site which would be more accurate:
HeaderStories headerStore = new HeaderStories( doc);
String header = headerStore.getHeader(pageNumber);
this should give you the header of the specified page. Same with footer:
HeaderStories headerStore = new HeaderStories( doc);
String footer = headerStore.getFooter(pageNumber);
If this dosen't work. I am not really into that API....
here a little Example for a very sloppy solution:
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i].equals("headerPageOne")){
int firstLineOfPageOne = i;
}
if (fileData[i]).equals("headerPageTwo"){
int lastLineOfPageOne = i
}
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
If you go with this i would recommend you to create a String[] with your headers and refractor the for-loop to a seperate getPages() Method. Therefore your loop would look like:
List<String> = new ArrayList<String>(Arrays.asList("header1","header2","header3","header4"));
for (int i = 0; i < fileData.length; i++)
{
//well there should be a loop for "x" too
if (fileData[i].equals(headerArray[x])){
int firstLineOfPageOne = i;
}
if (fileData[i]).equals(headerArray[x+1]){
int lastLineOfPageOne = i
}
}
You could create an Object(int pageStart, int PageStop), wich would be the product of your method.
I hope it helped you :)
I have for example 1000 images and their names are all very similar, they just differ in the number. "ImageNmbr0001", "ImageNmbr0002", ....., ImageNmbr1000 etc.;
I would like to get every image and store them into an ImageProcessor Array.
So, for example, if I use a method on element of this array, then this method is applied on the picture, for example count the black pixel in it.
I can use a for loop the get numbers from 1 to 1000, turn them into a string and create substrings of the filenames to load and then attach the string numbers again to the file name and let it load that image.
However I would still have to turn it somehow into an element I can store in an array and I don't a method yet, that receives a string, in fact the file path and returns the respective ImageProcessor that is stored at it's end.
Also my approach at the moment seems rather clumsy and not too elegant. So I would be very happy, if someone could show me a better to do that using methods from those packages:
import ij.ImagePlus;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;
I think I found a solution:
Opener opener = new Opener();
String imageFilePath = "somePath";
ImagePlus imp = opener.openImage(imageFilePath);
ImageProcesser ip = imp.getProcessor();
That do the job, but thank you for your time/effort.
I'm not sure if I undestand what you want exacly... But I definitly would not save each information of each image in separate files for 2 reasons:
- It's slower to save and read the content of multiple files compare with 1 medium size file
- Each file adds overhead (files need Path, minimum size in disk, etc)
If you want performance, group multiple image descriptions in single description files.
If you dont want to make a binary description file, you can always use a Database, which is build for it, performance in read and normally on save.
I dont know exacly what your needs, but I guess you can try make a binary file with fixed size data and read it later
Example:
public static void main(String[] args) throws IOException {
FileOutputStream fout = null;
FileInputStream fin = null;
try {
fout = new FileOutputStream("description.bin");
DataOutputStream dout = new DataOutputStream(fout);
for (int x = 0; x < 1000; x++) {
dout.writeInt(10); // Write Int data
}
fin = new FileInputStream("description.bin");
DataInputStream din = new DataInputStream(fin);
for (int x = 0; x < 1000; x++) {
System.out.println(din.readInt()); // Read Int data
}
} catch (Exception e) {
} finally {
if (fout != null) {
fout.close();
}
if (fin != null) {
fin.close();
}
}
}
In this example, the code writes integers in "description.bin" file and then read them.
This is pretty fast in Java, since Java uses "channels" for files by default
I'm studying Biomedical Informatics and I'm now doing my clinical practice, where I have to check that the charges made to hospitalized patients were performed correctly on supplies that are of unique charging (every procedure and supplies used have a codification).
I can import the Excel file on the software I'm doing but, I don't know now how to do the scan.
Here is the code (I'm doing it on NetBeans),
public class Portal extends javax.swing.JFrame {
private DefaultTableModel model;
public static int con = 0;
public ArrayList listas = new ArrayList();
public ArrayList listasr = new ArrayList();
public Portal() {
initComponents();
model = new DefaultTableModel();
jTable1.setModel(model);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser examinar = new JFileChooser();
examinar.setFileFilter(new FileNameExtensionFilter("Archivos Excel", "xls", "xlsx"));
int opcion = examinar.showOpenDialog(this);
File archivoExcel = null;
if(opcion == JFileChooser.APPROVE_OPTION){
archivoExcel = examinar.getSelectedFile().getAbsoluteFile();
try{
Workbook leerExcel = Workbook.getWorkbook(archivoExcel);
for (int hoja=0; hoja<leerExcel.getNumberOfSheets(); hoja++)
{
Sheet hojaP = leerExcel.getSheet(hoja);
int columnas = hojaP.getColumns();
int filas = hojaP.getRows();
Object data[]= new Object[columnas];
for (int fila=0; fila < filas; fila++)
{
for(int columna=0; columna < columnas; columna++)
{
if(fila==0)
{
model.addColumn(hojaP.getCell(columna, fila).getContents());
}
System.out.println(hojaP.getCell(columna, fila).getContents());
if(fila>=1)
data[columna] = hojaP.getCell(columna, fila).getContents();
}model.addRow(data);
}
}
model.removeRow(0);
JOptionPane.showMessageDialog(null, "Excel cargado exitosamente");
}
}
}
Before you import the excel file save it as a csv(comma delimited) file(remeber to delete the headings). Then open the netbeans project folder under my documents, then open the your project folder and dump the csv file in their. Look at your project under files in netbeans open the folder and you will see the file in their. Now you said you want to read the file/ scan the file.
You can use my method at first, understand it and adapt to other scenarios you have in the future.
First create a class or use an readily created( you already created java class).
Declare arrays depending on how many rows you had in the excel file not the csv file and a counter.
Example two.
String [] patientsnamess;
int [] ages;
int count;
Now initiate the arrays in a deafault constructor(you don't have to because you can do it when you declare them but it is conventional). You can learn about constructors there are two I know of or there are only two but I will only show a default constructor.
It will look like this.
public yourClassName(){
patientsnames = new String[400];//the number in square brackets are an example it sets the size of the array. You can set the size according to how many patients there are or you could just use lists as the limit on the list as dependent on primary and virtual memory.
ages = new int[400];
count = 0;
}
now create the method two read the text file.
public void readFile(){
count = 0;//important
Scanner contents = null;
try{
contents = new Scanner(new FileReader("You file's name.txt");
while(contents.hasNext()){
String a = contents.nextLine();
String p[]= a.split("\\;");
patientsnames[count] = p[0];
ages[count] = p[1];
count++;//important
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
}
Now create get methods to call up the arrays with the values from the file.(Find out on rest of stackoverflow).
Remeber that field types link up with the data in the file.
I really hope this works for you. If not I am sorry but good luck with your Biochemical Informatics course.
Remeber to call the readFile method with an object in this case or it won't work.
Research the neccessary imports such as:
import java.io.*;
import java.util.*;
currently i creating a java apps and no database required
that why i using text file to make it
the structure of file is like this
unique6id username identitynumber point
unique6id username identitynumber point
may i know how could i read and find match unique6id then update the correspond row of point ?
Sorry for lack of information
and here is the part i type is
public class Cust{
string name;
long idenid, uniqueid;
int pts;
customer(){}
customer(string n,long ide, long uni, int pt){
name = n;
idenid = ide;
uniqueid = uni;
pts = pt;
}
FileWriter fstream = new FileWriter("Data.txt", true);
BufferedWriter fbw = new BufferedWriter(fstream);
Cust newCust = new Cust();
newCust.name = memUNTF.getText();
newCust.ic = Long.parseLong(memICTF.getText());
newCust.uniqueID = Long.parseLong(memIDTF.getText());
newCust.pts= points;
fbw.write(newCust.name + " " + newCust.ic + " " + newCust.uniqueID + " " + newCust.point);
fbw.newLine();
fbw.close();
this is the way i text in the data
then the result inside Data.txt is
spencerlim 900419129876 448505 0
Eugene 900419081234 586026 0
when user type in 586026 then it will grab row of eugene
bind into Cust
and update the pts (0 in this case, try to update it into other number eg. 30)
Thx for reply =D
Reading is pretty easy, but updating a text file in-place (ie without rewriting the whole file) is very awkward.
So, you have two options:
Read the whole file, make your changes, and then write the whole file to disk, overwriting the old version; this is quite easy, and will be fast enough for small files, but is not a good idea for very large files.
Use a format that is not a simple text file. A database would be one option (and bear in mind that there is one, Derby, built into the JDK); there are other ways of keeping simple key-value stores on disk (like a HashMap, but in a file), but there's nothing built into the JDK.
You can use OpenCSV with custom separators.
Here's a sample method that updates the info for a specified user:
public static void updateUserInfo(
String userId, // user id
String[] values // new values
) throws IOException{
String fileName = "yourfile.txt.csv";
CSVReader reader = new CSVReader(new FileReader(fileName), ' ');
List<String[]> lines = reader.readAll();
Iterator<String[]> iterator = lines.iterator();
while(iterator.hasNext()){
String[] items = (String[]) iterator.next();
if(items[0].equals(userId)){
for(int i = 0; i < values.length; i++){
String value = values[i];
if(value!=null){
// for every array value that's not null,
// update the corresponding field
items[i+1]=value;
}
}
break;
}
}
new CSVWriter(new FileWriter(fileName), ' ').writeAll(lines);
}
Use InputStream(s) and Reader(s) to read file.
Here is a code snippet that shows how to read file.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("c:/myfile.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
// do something with the line.
}
Use OutputStream and Writer(s) to write to file. Although you can use random access files, i.e. write to the specific place of the file I do not recommend you to do this. Much easier and robust way is to create new file every time you have to write something. I know that it is probably not the most efficient way, but you do not want to use DB for some reasons... If you have to save and update partial information relatively often and perform search into the file I'd recommend you to use DB. There are very light weight implementations including pure java implementations (e.g. h2: http://www.h2database.com/html/main.html).
I'm trying to open MS Word 2003 document in java, search for a specified String and replace it with a new String. I use APACHE POI to do that. My code is like the following one:
public void searchAndReplace(String inputFilename, String outputFilename,
HashMap<String, String> replacements) {
File outputFile = null;
File inputFile = null;
FileInputStream fileIStream = null;
FileOutputStream fileOStream = null;
BufferedInputStream bufIStream = null;
BufferedOutputStream bufOStream = null;
POIFSFileSystem fileSystem = null;
HWPFDocument document = null;
Range docRange = null;
Paragraph paragraph = null;
CharacterRun charRun = null;
Set<String> keySet = null;
Iterator<String> keySetIterator = null;
int numParagraphs = 0;
int numCharRuns = 0;
String text = null;
String key = null;
String value = null;
try {
// Create an instance of the POIFSFileSystem class and
// attach it to the Word document using an InputStream.
inputFile = new File(inputFilename);
fileIStream = new FileInputStream(inputFile);
bufIStream = new BufferedInputStream(fileIStream);
fileSystem = new POIFSFileSystem(bufIStream);
document = new HWPFDocument(fileSystem);
docRange = document.getRange();
numParagraphs = docRange.numParagraphs();
keySet = replacements.keySet();
for (int i = 0; i < numParagraphs; i++) {
paragraph = docRange.getParagraph(i);
text = paragraph.text();
numCharRuns = paragraph.numCharacterRuns();
for (int j = 0; j < numCharRuns; j++) {
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
System.out.println("Character Run text: " + text);
keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
key = keySetIterator.next();
if (text.contains(key)) {
value = replacements.get(key);
charRun.replaceText(key, value);
docRange = document.getRange();
paragraph = docRange.getParagraph(i);
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
}
}
}
}
bufIStream.close();
bufIStream = null;
outputFile = new File(outputFilename);
fileOStream = new FileOutputStream(outputFile);
bufOStream = new BufferedOutputStream(fileOStream);
document.write(bufOStream);
} catch (Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
I call this function with following arguments:
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
When the Test.doc file contains a simple line like this : "AAA EEE", it works successfully, but when i use a complicated file it will read the content successfully and generate the Test1.doc file but when I try to open it, it will give me the following error:
Word unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and repair the file.
* Open the file with Text Recovery converter.
(C:\Test1.doc)
Please tell me what to do, because I'm a beginner in POI and I have not found a good tutorial for it.
First of all you should be closing your document.
Besides that, what I suggest doing is resaving your original Word document as a Word XML document, then changing the extension manually from .XML to .doc . Then look at the XML of the actual document you're working with and trace the content to make sure you're not accidentally editing hexadecimal values (AAA and EEE could be hex values in other fields).
Without seeing the actual Word document it's hard to say what's going on.
There is not much documentation about POI at all, especially for Word document unfortunately.
I don't know : is its OK to answer myself, but Just to share the knowledge, I'll answer myself.
After navigating the web, the final solution i found is :
The Library called docx4j is very good for dealing with MS docx file, although its documentation is not enough till now and its forum is still in a beginning steps, but overall it help me to do what i need..
Thanks 4 all who help me..
You could try OpenOffice API, but there arent many resources out there to tell you how to use it.
You can also try this one: http://www.dancrintea.ro/doc-to-pdf/
Looks like this could be the issue.