I try to get large arrays from java into matlab.
My problem ist, the java program is to large to run java in matlab, so I need to export the data from java and load it into matlab. Do anyone tried this?
This is how far I got:
I've wrote a class containing all values that should be exported
------- Export.java -------
import java.io.Serializable;
public class Export implements Serializable {
private double[][] values;
private String description;
public Export(String description,double[][] values){
this.description=description;
this.values=values;
}
public String getDescription(){return description;}
public double[][] getValues(){return values;}
}
--------------------------
And an main methode
------- StartPoint.java -------
public class StartPoint {
public static void main(String[] args) {
Export serial= new Export("description",new double[][]{{1,2},{3,4}});
OutputStream file;
try {
file = new FileOutputStream( "object.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
output.writeObject(serial);
output.close();
}
catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
System.out.println("done");
}
}
--------------------------
Accroding to http://www.weizmann.ac.il/matlab/techdoc/matlab_external/ch_java9.html the matlab-code should be easy, but I don't get ist. So any help for the matlab code would be great.
Thanks
To facilitate the import in Matlab I suggest that you write the data using the MAT-file format. Then you will be able to load the files into Matlab variables.
Related
I was wondering if it was possible to get an object from a FileInputStream without using ObjectInputStream.
Why am I doing this? I've been working on a project recently, it reads .DAT files from a game and converts them to .OBJ - There is a catch to these .DAT files however: Their stream header is ALWAYS 0xFACEAF0E. Is there a way I can get around the restriction ObjectInputStream has on stream headers and get an Object from one of these files?
Here is the code I need help with.
package xan_code;
/*
* Purpose: Determine file extension and run it through the code to move it to an OBJ.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import main.BeginConversion; //Import the conversion code. Returns a string based on the file
import xan_code.dathandler.ReadBinary; //Get the .DAT reading functions
#SuppressWarnings("serial")
public class HandleFiles extends Main { //Extend main to get the log from the opener UI.
static BeginConversion converter = new BeginConversion(); //Get the converter for XML files since this will also read XMLs derived from the .DAT
static String DatText = ""; //The "text" to return for the .DAT (To pack into the decoded file)
static Object _object; //THIS IS THE VARIABLE OF THE OBJECT I NEED IN ORDER TO CONVERT THE .DAT TO A MODEL
#SuppressWarnings("static-access")
public static String convert(File file, boolean isXML, FileInputStream FIS) { //Convert. Passes in the .DAT or .XML file, a boolean to whether or not its extension is .XML, and the FileInputStream from file
if (isXML) { //If it's an XML
String xml = ""; //This is the text to store the XML as a string
String obj = ""; //This is the text to store the WaveFront OBJ (Model format) as a string
try {
xml = new Scanner(file).useDelimiter("\\Z").next(); //use the scanner to get the string of the XML
obj = converter.BeginConvert(xml); //Pass the XML into the java files required to read from the XML and convert it to an OBJ. They return the text from an OBJ file.
} catch (Exception e) {
//Exceptions are handled before, though to be safe...
e.printStackTrace();
}
return obj; //Return that text to Main so I can create the file.
} else { //We have a .DAT
try {
//HELP REQUIRED HERE. NEED TO GET _object FROM THE FILE WITHOUT USING ObjectInputStream
DatText = ReadBinary.Read(file, _object); //Right now this actually returns the text of an XML, but that doesn't matter much at the moment.
} catch (IOException e) {
DatText = "Unexpected error while reading .DAT file!";
e.printStackTrace();
}
return DatText;
}
}
}
You can just strip off the extra bytes that ObjectInputStream should not see first with a FileInputStream.
static class MyObject implements Serializable{
int i;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
MyObject obj = new MyObject();
obj.i = 77;
File testFile = new File("test.dat");
try (FileOutputStream fos = new FileOutputStream(testFile)) {
fos.write(new byte[]{(byte) 0xFA, (byte) 0xCE, (byte) 0xAF, (byte) 0x0E});
try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(obj);
}
}
try (FileInputStream fis = new FileInputStream(testFile)) {
byte b4[] = new byte[4];
fis.read(b4);
try (ObjectInputStream ois = new ObjectInputStream(fis)) {
MyObject newObj = (MyObject) ois.readObject();
System.out.println("newObj.i = " + newObj.i);
}
}
}
my mainActivity has a ListView which should display my CustomList:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class CustomList implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<Game> list = new ArrayList<Game>();
public void add(Game toAdd){
list.add(toAdd);
}
public Game get(int id){
return list.get(id);
}
public ArrayList<Game> getList(){
return list;
}
public void serialize(){
try {
FileOutputStream fo = new FileOutputStream("res\\data.dat");
ObjectOutputStream ou = new ObjectOutputStream(fo);
ou.writeObject(list);
ou.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void deserialize(){
try {
FileInputStream fi = new FileInputStream("res\\data.dat");
ObjectInputStream oi = new ObjectInputStream(fi);
list = (ArrayList<Game>)oi.readObject();
oi.close();
fi.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I get the following error trying to serialize or desirialize:
java.io.FileNotFoundException: res\data.dat: open failed: ENOENT (No such file or directory)
My question is how to proper point to my data.dat file.
Thanks in advance
You can't write into the res directory (that's read-only), you have to write to somewhere else, e.g. to the cache directory (if it's only temporary; use context.getCacheDir() to get it's location) or to some permanent space (e.g. context.getFilesDir()).
You can get the file location like this, what you can pass to the FileOutputStream's or the FileInputStream's constructor:
File file = new File(context.getFilesDir(), "data.dat");
You may also have to request permission to write to external storage if you choose so.
Read more about storing files in Android here: http://developer.android.com/training/basics/data-storage/files.html
I am trying to write a hashset to a text file. Normally, I have no issues with writing to txt as it is simple for me. However, in this case I am absolutely clueless.
A bit of background about the class: it is a hashset of ComputerScientist objects with 2 fields; name, and field of research (and yes, I know what I put to fill up the hashset does not count, I was only trying to test to see if I could get this to work).
I know the basic setup to use filewriter to save strings to hashset which is what a lot of the similar questions which I found on SO dealt with, so those did not really help me.
I am eager to learn, and would appreciate it if snide or insulting comments were left out. And if there is already a similar question which deals with writing hashsets of objects to txt file, I apologize for not seeing it.
import java.util.HashSet;
import java.io.FileWriter;
import java.io.IOException;
/**
* Write a description of class ComputerScientistSet here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class ComputerScientistSet
{
private HashSet<ComputerScientist> computerScientistSet;
private FileWriter computerScientistWriter;
private String fileName;
/**
* Constructor for objects of class ComputerScientistSet
*/
public ComputerScientistSet(){
computerScientistSet = new HashSet<ComputerScientist>();
fileName = "scientist-names.txt";
setComputerScientistSet();
}
private void setComputerScientistSet(){
computerScientistSet.add (new ComputerScientist("Bob", "Robotics"));
computerScientistSet.add (new ComputerScientist("Tim", "VR"));
computerScientistSet.add (new ComputerScientist("Jake", "Nuclear Fision"));
computerScientistSet.add (new ComputerScientist("Joe", "Snapple"));
computerScientistSet.add (new ComputerScientist("Jane", "Magnets"));
computerScientistSet.add (new ComputerScientist("Mary", "PC"));
}
public void writeNames(){
try{
computerScientistWriter = new FileWriter(fileName, true);
computerScientistWriter.write(computerScientistSet);
computerScientistWriter.close();
}
catch(IOException ioException){
System.out.println("Error.");
}
}
}
Update:
Would it help if I include the following code? I am still working out what would go in the parentheses by the .write() line. My brain is fried :/
for (int i = 0; i < computerScientistSet.size(); i++) {
computerScientistWriter.write();
}
Since I assume you want to write the set to a file to read it in later, the best way would be not to reinvent the wheel and to use serialization instead.
public class Person implements java.io.Serializable {
private String name;
// constructor, setter, getter, etc
}
public static void main(String[] args) {
Set<Person> persons = new HashSet<Person>();
persons.add(new Person("foo");
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/persons.data");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("/tmp/persons.data");
ObjectInputStream in = new ObjectInputStream(fileIn);
Set<Person> persons = (Set<Person>) in.readObject();
in.close();
fileIn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
Ended up using this coding:
public void writeNames(){
try{
computerScientistWriter = new FileWriter(fileName, true);
for(ComputerScientist list: computerScientistSet){
computerScientistWriter.write(list.getName() + " , " + "\n" + list.getField() + System.lineSeparator() );
}
computerScientistWriter.close();
}
catch(IOException ioException){
System.out.println("Error.");
}
}
Based on your comments here your output currently shows many entries as: ComputerScientist#7e384e79
Rather than rely on that link, I strongly encourage you to update this question with an example of what your code here would currently output.
When you see output like ComputerScientist#7e384e79 it means the ComputerScientist class isn't overriding the toString() method to show it's state. You can do that to make your technique work. You can do it by hand or use a IDE that offers a refactoring to make it less tedious but you don't get it for free. You'll need it implemented for every class you wish to output this way.
package healthbuddy;
/**
*
* #author tpzap_000
*/
import java.io.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.util.List;
import java.util.Scanner;
public class PersistentDataModelCntl implements Serializable{
private File theFile = new File("PDM.txt");
private XStream xstream = new XStream(new StaxDriver());
public static PersistentDataModelCntl thePDMCntl;
private PersistentDataModel thePDM;
public PersistentDataModelCntl(){
this.readPDMFile();
}
public static PersistentDataModelCntl getPDMCntl(){
if(thePDMCntl == null){
thePDMCntl = new PersistentDataModelCntl();
}
return thePDMCntl;
}
public void readPDMFile(){
try
{
System.out.println("in read file");
StringBuilder fileContents = new StringBuilder();
Scanner in = new Scanner(theFile);
String tempXML;
boolean test = in.hasNextLine();
System.out.println(test);
while(in.hasNextLine()){
fileContents.append(in.nextLine());
System.out.println("reading file contents");
}
tempXML = fileContents.toString();
thePDM = (PersistentDataModel)xstream.fromXML(tempXML);
}
//If the file does not exist, thePDM is instantiated to be a new, empty, PDM file. The file is then written to disk, and then read from disk
// using some recursive stuff. Also creates a test UserList so that I don't get a NullPointerException in the LoginCntl.
catch(FileNotFoundException ex){
System.out.println("FileNotFound");
thePDM = new PersistentDataModel();
thePDM.thePDMFoodList = new FoodList();
thePDM.thePDMMealList = new MealList();
thePDM.thePDMDietList = new DietList();
thePDM.thePDMDiet = new Diet();
//Creates new attributes if things are null.
this.writePDMFile();
this.readPDMFile();
System.out.println("FileNotFound Exception");
}
catch(IOException ex){
System.out.println("IO Exception");
ex.printStackTrace();
}
}
//Problem Code is here:
public void writePDMFile(){
try{
String xml = xstream.toXML(thePDM);
PrintWriter writer = new PrintWriter(theFile);
System.out.println(xml);
writer.println(xml);
}
catch(Exception ex){
System.out.println("There was a problem writing the file.");
}
}
public PersistentDataModel getPDM(){
return thePDM;
}
}
Above is my code. I currently have an app that uses object serialization for it's data persistence, but I'm in the process of converting it to XML. I'm using the Xstream library to create the XML, but I'm having some trouble writing it to disc. Xstream gives me the XML as a String, which I then attempt to write to a text file using PrintWriter. However the text file is empty, but the String I'm attempting to write to it is not. My understanding of PrintWriter is such that you supply it the file name it should be writing to, it attempts to write to that file(creates it if it does not exist), and then it should write the contents of the String to the file.
Any assistance would be greatly appreciated. Not sure where I'm going wrong.
You need to add
writer.close()
to the end of your code. The writer only writes to file when it is closed.
You need to call PrintWriter::flush() or PrintWriter::close().
Try to close PrintWriter after you wrote xml to file
I'm an idiot. I didn't call close on my PrintWriter.
This is for a homework I'm doing on my walk learning java.
I'm writing a program and it is all working as expected except the read/write to file.
I have one class named Medico that holds only one string (typeOfMedico) and one int (valorFacturado). Medico is a sub class of Pessoa. Pessoa holds data like name and address. public class Medico extends Pessoa implements Serializable is the main function on Medicoclass.
On my main class, named Clinica, I ask for user input and at the end of I create a new Medico that its added to an Arraylist named medico.
For reading and writing to file I've created this class:
package clinica;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FicheiroObjectos {
private ObjectInputStream iS;
private ObjectOutputStream oS;
public void abreLeitura(String nomeDoFicheiro) throws IOException {
iS = new ObjectInputStream(new FileInputStream(nomeDoFicheiro));
}
public void abreEscrita(String nomeDoFicheiro) throws IOException {
oS = new ObjectOutputStream(new FileOutputStream(nomeDoFicheiro));
}
public Object leObjecto() throws IOException, ClassNotFoundException {
return iS.readObject();
}
public void escreveObjecto(Object o) throws IOException {
oS.writeObject(o);
}
public void fechaLeitura() throws IOException {
iS.close();
}
public void fechaEscrita() throws IOException {
oS.close();
}
public void leFicheiroMedicos() {
Medico medicos;
while (true) {
try {
medicos = (Medico) this.leObjecto();
Clinica.medicos.add(medicos);
} catch (EOFException eof) {
break;
} catch (ClassNotFoundException cnf) {
System.out.print("\nClassNotFoundException!\nO programa vai terminar\n");
System.exit(-1);
} catch (IOException ioe) {
System.out.print("\nErro ao ler o ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
public void escreveFicheiroMedicos() {
try {
for (Medico medicos: Clinica.medicos) {
this.escreveObjecto(medicos);
}
} catch (IOException e) {
System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
On my main class I've created this two functions:
public static void insereDadosExistentes() {
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreLeitura("Medicos.dat");
file.leFicheiroMedicos();
file.fechaLeitura();
} catch (IOException ioe) {
}
}
public static void gravarMedicos() {
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreEscrita("Medicos.dat");
file.escreveFicheiroMedicos();
file.fechaEscrita();
} catch (IOException e) {
System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
Then added insereDadosExistentes() at the beginning of my mainfunction and added gravarMedicos() just after adding a Medico to my medicos arraylist.
When I run my program (On the first run, file Medicos.dat, does not exist) and create a Medico, Medico is added to my arraylist and the file Medicos.dat is created. Then I stop the program and on the next run, which now haves a Medicos.dat file, I get the error:
Erro ao ler o ficheiro!
O programa vai terminar
The problem is in writing the file or reading the file?
I know the error is given when reading the file but it could be because the writhing to file is not properly executed.
If I try to open Medicos.dat I can see some characters but nothing related with the info I input so I don't even know if the file writing is ok.
Remember that all besides file handling is working as expected.
Can you point me In some directions?
favolas
Make sure that you explicitly close the ObjectOutputStream so that all the data is written.
Your problem is an IOException. However, the backtrace will tell you what's going on: trouble opening, reading, what? you can call printStackTrace(), but better you can use a debugging and just look at the stack trace.
If you catch an exception dont just write something to system.out but print the stacktrace this will usually give you a clue whats wrong
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreEscrita("Medicos.dat");
file.escreveFicheiroMedicos();
file.fechaEscrita();
} catch (IOException e) {
e.printStackTrace();
}
Q: Are you trying to read and write DATA, or are you trying to serialize and deserialize OBJECTS?
I think all you need to do is open and write to a simple text file:
For example:
http://www.exampledepot.com/egs/java.io/AppendToFile.html
import java.io.*;
public class TestFile
{
public static void main (String[] args)
{
// Test "append"
// SOURCE: http://www.exampledepot.com/egs/java.io/AppendToFile.html
try {
BufferedWriter out =
new BufferedWriter(
new FileWriter("myfile.txt", true));
out.write("testing: a b c\n");
out.write("testing: d e f\n");
out.close();
}
catch (IOException e) {
}
}
}
Sample output:
testing: a b c
testing: d e f
I don't know Java's serialization stuff at all, but this seems "too easy":
public void escreveObjecto(Object o) throws IOException {
oS.writeObject(o);
}
How is the object output stream supposed to know what portions of your object needs to be written to disk? Could be that your object contains nothing but computed values that shouldn't be stored. Could be that your object's data needs to be stored completely. Perhaps references to String objects should just be dropped... or perhaps those Strings should be written to disk.
There must be more to using the ObjectStream stuff than you're showing here -- and paulsm4's answer shows how writing your own content by hand isn't too bad. Should you be taking that approach instead? Does your class have a defined storage format that you must adhere to?