java write class to file - java

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?

Related

How to write text to a next empty line in text file in java

package ideat;
import java.nio.file.Paths;
import java.io.FileWriter;
import java.util.Scanner;
public class Paaohjelma {
public static void main(String[] args) {
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt");
for (String line = tLuk.nextLine(); line.isBlank(); tKirj.append("\n")) {
tKirj.write("textHere");
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I created a loop that goes trough the txt-file until it finds an empty line to write, however this doesn't work because when Scanner tries to read next line that is empty, java throws no next line exception. The purpose of the program is to add and save new ideas to a text file and that is why I don't want to overwrite existing lines of text.
Once you open a file you are reading in write mode, a file descriptor for reading is corrupted. It could be not corrupted, but once written something, it will be corrupted especially when what the descriptor will read overwritten.
So, you should take rewrite and replace approach:
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt.tmp");
while (tLuk.hasNextLine()) {
String line = tLuk.nextLine();
if (line.isBlank()) {
tKirj.write("textHere");
} else {
tKirj.write(line);
}
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
Then, replace the file ideat.txt with ideat.txt.tmp.
Files.move(
Paths.get("ideat.txt.tmp"),
Paths.get("ideat.txt"),
StandardCopyOption.REPLACE_EXISTING
);

How to write lines to a file in java while the script is executing

I am trying to write strings to a file but all the strings are being written to the file once the script is terminated.
To make my problem clear, in the below code I want to write a single string to my files per second and my file should be updated each second. Please help I am new to java.
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException {
String[] list = "Should write each word in each iteration".split("\\s");
for(String word:list){
Writer obj = new Writer();
obj.func(word);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
class Writer{
public void func(String word) throws IOException{
FileWriter writer = new FileWriter("file" , true);
writer.write(word);
writer.close();
}
}

BufferedWriter without try method IOException

I know this topic has been discussed a lot and I have already read a lot of posts here about that, but I still seem to have trouble.
My problem is that I am also a beginner and I don't really understand how ĸwork and the try and catch function.
I have been trying to write to a file some string array, but it doesn't appear in there, nor the catch error is displayed in the console. I don't want to use the try method in this case, because when I am, I cannot use the variable declared for let's say BufferedWriter in other places, I am only restricted to the try method. Otherwise, I get a bug.
This is my code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try(BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))) {
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
System.err.println("Idk when should this appear?");
}
}
}
For the "can't use it anywhere" part of your problem, you could declare the variable outside of the try catch block and only assign it inside. You can do a null check wherever else you want to use it to make sure there's no problems, or assign it another value in the catch block. Like so:
public static void main(String[] args) {
BufferedWriter writer;
String[] anything;
try {
writer = new BufferedWriter(new FileWriter("testing.txt"))) {
anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for (String mem: anything) {
writer.append(mem);
}
writer.close();
} catch (IOException e) {
writer = null;
e.printstacktrace();
}
}
}
if(writer != null){
System.out.println(writer);
}
try and catch it's use for managed the exception. try this code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The System.err.println("Idk when should this appear?"); appear when you have an Exception in your try "an Error".

Sending iDOC from Java to SAP

We have iDOC files that are generated from our system. Now we are trying to send them to SAP via RFC connection. I already etablished an RFC connection AS A CLIENT but i am unable to send iDOC!
I tried to create a sample iDOC to test it but it doesn't work!
Exception in thread "main" java.lang.NoSuchMethodError: com.sap.conn.idoc.jco.SAPRepository$ConnectionProvider.execute(Lcom/sap/conn/jco/JCoFunction;Lcom/sap/conn/jco/rt/AbapRepository;)V
at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData40(SAPRepository.java:1204)
at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData(SAPRepository.java:1110)
at com.sap.conn.idoc.jco.SAPRepository.getRootSegmentMetaData(SAPRepository.java:909)
at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:124)
at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:61)
at com.sap.conn.idoc.jco.JCoIDocDocument.<init>(JCoIDocDocument.java:51)
at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:133)
at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:35)
at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:175)
at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:18)
at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:49)
I even tried to send a sample iDOC XML but i am also facing another error, tried to change the XML many times but i am facing the same problem again an again!
com.sap.conn.idoc.IDocParseException: (7) IDOC_ERROR_PARSE_FAILURE: Invalid character encountered in XML input data source:
state=READING_XMLDECLARATION, charPosition=14, lineNumber=1, columnNumber=15, invalidChar=U+003D,
sourceSnippet=...#<?xml version="1.0" encoding="UTF-8"?><DEBMAS06><IDOC><EDI_DC40><DOCNUM>20120114120000</DOCNUM><IDO...
^
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.throwIDocParseException(DefaultIDocXMLParser.java:2223)
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parseProlog(DefaultIDocXMLParser.java:1635)
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parse(DefaultIDocXMLParser.java:320)
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:112)
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:54)
at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:31)
at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:57)
This is the code i am using to create the iDOC and send the iDOC XML:
package com.idoc.sender;
import com.sap.conn.idoc.*;
import com.sap.conn.idoc.jco.JCoIDoc;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import java.io.BufferedReader;
import java.io.FileReader;
public class IDocClientExample {
public static void main(String[] args) {
try {
String iDocXML = null;
FileReader fileReader;
try {
fileReader = new FileReader("TestSalesOrder.xml");
BufferedReader br = new BufferedReader(fileReader);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
iDocXML = sb.toString();
br.close();
fileReader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// see provided configuration file xxxx.jcoDestination
JCoDestination destination = JCoDestinationManager.getDestination("xxxx");
IDocRepository iDocRepository = JCoIDoc.getIDocRepository(destination);
String tid = destination.createTID();
IDocFactory iDocFactory = JCoIDoc.getIDocFactory();
System.out.println(destination.getAttributes());
// a) create sample new idoc
IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
IDocSegment segment = doc.getRootSegment();
segment.addChild("E1MARAM");
JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
// b) use existent xml file
IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
destination.confirmTID(tid);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("program end");
}
}
// a) create sample new idoc
IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
IDocSegment segment = doc.getRootSegment();
segment.addChild("E1MARAM");
JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
// b) use existent xml file
IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
destination.confirmTID(tid);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("program end");
}
}
This is my connection file:
jco.client.lang=EN
jco.client.client=100
jco.client.passwd=xxxx
jco.client.user=xxxx
jco.client.sysnr=01
jco.client.ashost=xxxx
This is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<DEBMAS06>
<IDOC>
<EDI_DC40>
<DOCNUM>20120114120000</DOCNUM><IDOCTYP>DEBMAS06</IDOCTYP>
<MESTYP>DEBMAS</MESTYP>
<SNDPOR>HTTPDEMO</SNDPOR>
<SNDPRT>LS</SNDPRT>
<SNDPRN>HTTPDEMO</SNDPRN>
<RCVPOR>SAPxxx</RCVPOR>
<RCVPRT>LS</RCVPRT>
<RCVPRN>xxxCLNT100</RCVPRN>
</EDI_DC40>
<E1KNA1M segment="1">
<KUNNR>47</KUNNR>
<NAME1>Test Customer</NAME1>
<KTOKD>0004</KTOKD>
<SORTL>TEST</SORTL>
<ORT01>City</ORT01>
<LAND1>PL</LAND1>
<LZONE>A</LZONE>
<SPRAS>L</SPRAS>
<STRAS>Street</STRAS>
</E1KNA1M>
</IDOC>
</DEBMAS06>
I am using sapjco3-x86-64bit-3.0.5 and sapidoc-3.0.1!
Testing the creation of iDOC and sending IDOC XML is just for test but in our case, we have the iDOC ready!
My question is, how can i send iDOC directly from my disk to SAP via RFC? If i can't do so, how can i slove the error of creating iDOC or sending iDOC XML? My second question, once i am able to send iDOC, do i have to etablish a new SERVER RFC connection so i can receive iDOC from SAP?
** EDIT **
Now i ma able to send and receive IDoc properly. My problem is how i can get the IDoc as a Flat IDoc.
I can receive my IDoc as XML IDoc with this code:
package com.idoc.actif;
import com.sap.conn.idoc.IDocDocumentList;
import com.sap.conn.idoc.IDocXMLProcessor;
import com.sap.conn.idoc.jco.*;
import com.sap.conn.jco.server.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class IDocServerExample
{
public static void main(String[] a)
{
try
{
// see provided examples of configuration files xxxx.jcoServer and xxxx.jcoDestination
JCoIDocServer server = JCoIDoc.getServer("xxxx");
server.setIDocHandlerFactory(new MyIDocHandlerFactory());
server.setTIDHandler(new MyTidHandler());
MyThrowableListener listener = new MyThrowableListener();
server.addServerErrorListener(listener);
server.addServerExceptionListener(listener);
//server.setConnectionCount(1);
server.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
static class MyIDocHandler implements JCoIDocHandler
{
public void handleRequest(JCoServerContext serverCtx, IDocDocumentList idocList)
{
FileOutputStream fos=null;
OutputStreamWriter osw=null;
try
{
//receiving XML IDoc, how to get the IDoc as a Flat IDoc (SAP is sending the IDoc as Flat)???
IDocXMLProcessor xmlProcessor = JCoIDoc.getIDocFactory().getIDocXMLProcessor();
fos=new FileOutputStream(serverCtx.getTID());
osw=new OutputStreamWriter(fos, "UTF8");
xmlProcessor.render(idocList, osw, IDocXMLProcessor.RENDER_WITH_TABS_AND_CRLF);
osw.flush();
}
catch (Throwable thr)
{
thr.printStackTrace();
}
finally
{
try
{
if (osw!=null)
osw.close();
if (fos!=null)
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
static class MyIDocHandlerFactory implements JCoIDocHandlerFactory
{
private JCoIDocHandler handler = new MyIDocHandler();
public JCoIDocHandler getIDocHandler(JCoIDocServerContext serverCtx)
{
return handler;
}
}
static class MyThrowableListener implements JCoServerErrorListener, JCoServerExceptionListener
{
public void serverErrorOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Error error)
{
System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
error.printStackTrace();
}
public void serverExceptionOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Exception error)
{
System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
error.printStackTrace();
}
}
static class MyTidHandler implements JCoServerTIDHandler
{
public boolean checkTID(JCoServerContext serverCtx, String tid)
{
System.out.println("checkTID called for TID="+tid);
return true;
}
public void confirmTID(JCoServerContext serverCtx, String tid)
{
System.out.println("confirmTID called for TID="+tid);
}
public void commit(JCoServerContext serverCtx, String tid)
{
System.out.println("commit called for TID="+tid);
}
public void rollback(JCoServerContext serverCtx, String tid)
{
System.out.print("rollback called for TID="+tid);
}
}
}
I guess that there is an incompatibility between the two SAP libraries that you use. I recommend to install the latest patch levels first. Currently this is JCo version 3.0.17 and the Java IDoc Library 3.0.12.
I only do not understand what you are doing with the StringBuffer here. If you would like to read IDoc-XML from a file, then the IDocXMLProcessor offers appropriate parse methods for this - the best would be
IDocXMLProcessor.parse(IDocRepository repository, InputStream xmlStream)
so that it also can take care of different file encodings as specified in the contained XML encoding attribute. If you choose a java.io.Reader or a String then you have to take care for this on your own (which you don't do in your example).
But in principle your code doesn't seem to be wrong at first sight.
In contrast to the IDoc-XML itself which is lacking the mandatory BEGIN="1" and SEGMENT="1" attributes for the <IDOC> and <EDI_DC40> tags.

export Java object and import it into matlab

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.

Categories