flexicapture processor recognize only first page of document - java

I'm using flexicapture processor for recognizing my document. I've a case where i've a document with multiple pages i.e. a document have multiple images and each image is need to recognize.
I'm following below procedure to achieve my general task ,either one image in document or multiple image in a document;
create a processor
add document definition file or afl file
run recognition as IDocument document = processor.RecognizeNextDocument();
But when it return a document, document, it has only one page,which is the first page of document, why is it so?
On the other case, if i use project instead processor,IProject, with below procedure
create a project
get batches from project project.getBatches(),
add a document (that have multiple page) to batch
recognize them
The i've all pages information of document,IDocuments documents = batch.getDocuments(),
How i can achieve the same task wit processor? I want processor recognize all pages in a document and return a document with all pages in it. ?
if something is unclear, pls ask for more information.
Please reply asap...
Code :1 using flexicapture processor
/**
*
*/
/**
* #author Nitin
*
*/
import java.sql.BatchUpdateException;
import com.abbyy.FCEngine.*;
public class FlexicaputreVerificationUsingProcessor {
private static Object verificationWorkSet(Object object) {
// TODO Auto-generated method stub
return null;
}
private static void trace( String txt )
{
System.out.println( txt );
}
static private String samplesFolder;
static private String projectFolder;
static private String serialNumber;
static private String dllPath;
static {
samplesFolder = "C:\\ProgramData\\ABBYY\\SDK\\10\\FlexiCapture Engine\\Samples\\";
projectFolder = "C:\\Users\\Nitin\\FlexicaptureTest\\flexiverificationtest" ;
try {
java.io.FileInputStream file = new java.io.FileInputStream( samplesFolder + "SampleConfig\\SamplesConfig.txt" );
java.io.BufferedReader reader = new java.io.BufferedReader( new java.io.InputStreamReader( file ) );
serialNumber = reader.readLine();
dllPath = reader.readLine();
file.close();
} catch( java.io.IOException e ) {
System.out.println( e.getMessage() );
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// Load Engine
try {
trace("Loading engine");
IEngineLoader engineLoader= Engine.CreateEngineOutprocLoader();
IEngine engine = engineLoader.Load(serialNumber,dllPath);
try {
// Create and configure FlexiCaptureProcessor
trace("Creating and configureing FlexiCaptureProcessor");
IFlexiCaptureProcessor processor = engine.CreateFlexiCaptureProcessor();
processor.AddDocumentDefinitionFile( projectFolder + "\\Document_Definition_1.fcdot" );
trace("Adding images/pdf to processor");
final int fileCount = 1 ;
processor.AddImageFile(projectFolder + "\\don't upload to big .pdf");
engine.EnableRecognitionVariants( true );
trace("Creating Document collection");
IDocumentsCollection documentsCollection = engine.CreateDocumentsCollection();
trace( "Reconizing Images/pdfs..." );
int totalErrors = 0 ;
for ( int iterator = 0 ; iterator<fileCount; iterator++ ){
trace("Recongnizing image/pdf number: " +(iterator+1));
IDocument document = processor.RecognizeNextDocument();
trace("Getting last processing error for checksum");
IProcessingError lastProcessingError = processor.GetLastProcessingError() ;
if ( lastProcessingError !=null)
{
String errormsg = lastProcessingError.MessageText();
totalErrors++;
trace("Error occured while recognizeing document, Document number: "+(iterator+1)+ " with Error msg: "+errormsg);
//since we are not handling error (right now) so moving to next document for recognization
processor.ResumeProcessing(false);
}else {
trace("No error occured while recognization of document number : "+(iterator+1));
}
trace("Adding documents in Documents collection");
documentsCollection.Add(document);
}
if ( totalErrors == fileCount){
trace("Facing Error for all document while recongnization");
return ;
}
trace("Creaing Verification session");
try {
IVerificationSession verificationSession = engine.CreateVerificationSession(documentsCollection) ;
try {
//enabling context verification
verificationSession.getOptions().setVerifyFields(true);
//disabling group verification
verificationSession.getOptions().setVerifyBaseSymbols(false);
verificationSession.getOptions().setVerifyExtraSymbols(false);
try {
trace("Get NextWork Set");
IVerificationWorkSet verificationWorkSet = verificationSession.NextWorkSet();
if ( verificationWorkSet == null){
trace("first verificationWork set is null");
}else {
//process each work set in Verification session
trace("Processing Work Set");
while ( verificationWorkSet != null ){
try{
trace("Geting Verification group");
//get next group for verification
IVerificationGroup verificationGroup = verificationWorkSet.NextGroup();
if ( verificationGroup == null ){
trace("First verification group is null");
}else {
trace("processing each group of a workset");
//processing each group of a work set
while ( verificationGroup!= null){
int verificationObjectInAGroupCount = verificationGroup.getCount();
trace("Total number of verification object: " +verificationObjectInAGroupCount);
for ( int iterator = 0; iterator<verificationObjectInAGroupCount; iterator++){
trace ( "getting and Processing "+(iterator +1 ) + " verification object of A group");
//getting verification object
IVerificationObject verificationObject = verificationGroup.getElement(iterator);
if ( verificationObject == null){
trace("verification object is null");
}else {
if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Group ) {
IGroupVerificationObject groupVerificationObject = verificationObject.AsGroupVerificationObject();
if ( groupVerificationObject == null){
System.out.println("group verification object is null ");
}
}else if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Context) {
IContextVerificationObject contextVerificationObject = verificationObject.AsContextVerificationObject();
if ( contextVerificationObject == null){
trace("ContextVerification object is null");
}else {
IField field = contextVerificationObject.getField();
if ( field == null){
trace("field getting null");
}else {
System.out.println(" field full name: " +field.getFullName() + "\n Name: " +field.getName());
IFieldValue fieldValue = field.getValue();
if ( fieldValue == null){
trace("Field Value is Null");
}else {
trace ( "getting text from field value");
IText text = fieldValue.getAsText() ;
if ( text == null){
trace("text getting null in field value");
}else {
int wordCount = text.getRecognizedWordsCount() ;
trace("recognized word count: "+wordCount);
//getting words from text
for ( int wordIndex = 0 ; wordIndex<wordCount; wordIndex++ ){
trace ("processing word number :" +wordIndex);
IRecognizedWordInfo recognizedWordInfo = engine.CreateRecognizedWordInfo() ;
if ( recognizedWordInfo == null){
trace("Can't create recognizedWordInfo object using engine");
}else {
text.GetRecognizedWord(wordIndex, -1, recognizedWordInfo);
//getting characters from word
for (int characterIndex = 0 ; characterIndex<recognizedWordInfo.getText().length(); characterIndex++ ){
trace("processing character number : " +characterIndex);
IRecognizedCharacterInfo recognizedCharacterInfo = engine.CreateRecognizedCharacterInfo();
if ( recognizedCharacterInfo == null) {
trace("can't create recognizedCharacterInfo object");
}else {
recognizedWordInfo.GetRecognizedCharacter(characterIndex, -1, recognizedCharacterInfo);
System.out.println(" Character: " + recognizedCharacterInfo.getCharacter());
System.out.println(" Confidence level : " +recognizedCharacterInfo.getCharConfidence());
}
}
}
}
}
System.out.println(" Field Value : " +fieldValue.getAsString());
}
}
}
}
}
}
trace("Geting next Verification group");
verificationGroup = verificationWorkSet.NextGroup();
}
}
}catch (Exception e){
trace("Exception occured in getting next work group");
e.printStackTrace();
}
trace("Get next worksets");
//get next work set
verificationWorkSet = verificationSession.NextWorkSet();
}
}
}catch (Exception e){
e.printStackTrace();
}
}finally {
trace("closing Verification object");
verificationSession.Close();
}
} catch (Exception e) {
trace("Exception occured in creating verification sessions");
}
}catch (Exception e){
trace ("Exception occured in");
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
trace("unloading Engine");
Engine.Unload();
}
}
}
Code : 2 using project
import java.io.File;
import java.io.IOException;
import java.sql.BatchUpdateException;
import com.abbyy.FCEngine.*;
public class VerificationStep {
//same as above
public static void main( String[] args )
{
// Load Engine
try {
trace("Loading engine");
IEngineLoader engineLoader= Engine.CreateEngineOutprocLoader();
IEngine engine = engineLoader.Load(serialNumber,dllPath);
try{
IProject project = engine.OpenProject( projectFolder + "\\flexitest.fcproj" );
try {
IBatch batch = null ;
trace( "Creating Batch..." );
IBatches batchs = project.getBatches();
if (batchs == null || batchs.getCount() == 0){
batch = project.getBatches().AddNew("TestBatch");
}
batch = batchs.getElement(0);
assert(batch == null);
try{
trace("opening batch");
batch.Open();
trace( "Adding pdfs..." );
batch.AddImage(projectFolder + "\\don't upload to big .pdf");
trace( "Reconizing pdfs..." );
batch.Recognize(null, RecognitionModeEnum.RM_ReRecognizeAll,null);
trace("Creating Verification object");
try {
IVerificationSession verificationSession = project.StartVerification(null);
try {
//enabling context verification
verificationSession.getOptions().setVerifyFields(true);
//disabling group verification
verificationSession.getOptions().setVerifyBaseSymbols(false);
verificationSession.getOptions().setVerifyExtraSymbols(false);
try {
trace("Get NextWork Set");
IVerificationWorkSet verificationWorkSet = verificationSession.NextWorkSet();
if ( verificationWorkSet == null){
trace("first verificationWork set is null");
}else {
//process each work set in Verification session
trace("Processing Work Set");
while ( verificationWorkSet != null ){
try{
trace("Geting Verification group");
//get next group for verification
IVerificationGroup verificationGroup = verificationWorkSet.NextGroup();
if ( verificationGroup == null ){
trace("First verification group is null");
}else {
trace("processing each group of a workset");
//processing each group of a work set
while ( verificationGroup!= null){
int verificationObjectInAGroupCount = verificationGroup.getCount();
trace("Total number of verification object: " +verificationObjectInAGroupCount);
for ( int iterator = 0; iterator<verificationObjectInAGroupCount; iterator++){
trace ( "getting and Processing "+(iterator +1 ) + " verification object of A group");
//getting verification object
IVerificationObject verificationObject = verificationGroup.getElement(iterator);
if ( verificationObject == null){
trace("verification object is null");
}else {
if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Group ) {
IGroupVerificationObject groupVerificationObject = verificationObject.AsGroupVerificationObject();
if ( groupVerificationObject == null){
System.out.println("group verification object is null ");
}
}else if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Context) {
IContextVerificationObject contextVerificationObject = verificationObject.AsContextVerificationObject();
if ( contextVerificationObject == null){
trace("ContextVerification object is null");
}else {
IField field = contextVerificationObject.getField();
if ( field == null){
trace("field getting null");
}else {
System.out.println(" field full name: " +field.getFullName() + "\n Name: " +field.getName());
IFieldValue fieldValue = field.getValue();
if ( fieldValue == null){
trace("Field Value is Null");
}else {
trace ( "getting text from field value");
IText text = fieldValue.getAsText() ;
if ( text == null){
trace("text getting null in field value");
}else {
int wordCount = text.getRecognizedWordsCount() ;
trace("recognized word count: "+wordCount);
//getting words from text
for ( int wordIndex = 0 ; wordIndex<wordCount; wordIndex++ ){
trace ("processing word number :" +wordIndex);
IRecognizedWordInfo recognizedWordInfo = engine.CreateRecognizedWordInfo() ;
if ( recognizedWordInfo == null){
trace("Can't create recognizedWordInfo object using engine");
}else {
text.GetRecognizedWord(wordIndex, -1, recognizedWordInfo);
//getting characters from word
for (int characterIndex = 0 ; characterIndex<recognizedWordInfo.getText().length(); characterIndex++ ){
trace("processing character number : " +characterIndex);
IRecognizedCharacterInfo recognizedCharacterInfo = engine.CreateRecognizedCharacterInfo();
if ( recognizedCharacterInfo == null) {
trace("can't create recognizedCharacterInfo object");
}else {
recognizedWordInfo.GetRecognizedCharacter(characterIndex, -1, recognizedCharacterInfo);
System.out.println(" Character: " + recognizedCharacterInfo.getCharacter());
System.out.println(" Confidence level : " +recognizedCharacterInfo.getCharConfidence());
}
}
}
}
}
System.out.println(" Field Value : " +fieldValue.getAsString());
}
}
}
}
}
}
verificationGroup = verificationWorkSet.NextGroup();
}
}
}catch (Exception e){
e.printStackTrace();
}
//get next work set
verificationWorkSet = verificationSession.NextWorkSet();
}
}
}catch (Exception e){
e.printStackTrace();
}
}finally {
verificationSession.Close();
}
}catch (Exception e){
e.printStackTrace();
}
trace ("Getting Documents");
IDocuments documents = batch.getDocuments();
trace ("Getting Fields and printing");
for ( int j = 0 ; j < documents.getCount(); j++){
trace ("Getting documnets:" +(j+1));
IDocument document = documents.getElement(j);
IDocumentDefinition definition = document.getDocumentDefinition();
assert( definition != null );
assert( document.getPages().getCount() == 1 );
trace( "DocumentType: " + document.getDocumentDefinition().getName() );
try {
trace("opening document");
document.Open(true);
IFields fields = document.getSections().Item( 0 ).getChildren();
for( int i = 0; i < fields.getCount(); i++ ) {
IField field = fields.getElement( i );
trace( field.getName() + ": " +
( field.getValue() != null ? field.getValue().getAsString() : "." ) );
}
}finally {
trace("closing document");
document.Close(true);
}
}
}finally {
trace("Closing Batch");
batch.Close();
}
}catch (Exception e){
System.out.println("Exception in creating Batch");
e.printStackTrace();
}
finally {
trace("closing project");
project.Close();
}
}catch (Exception e){
System.out.println("Exception occured while loading project");
e.printStackTrace();
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("Exception occured while loading engine");
e.printStackTrace();
}
finally {
trace("unloading Engine");
Engine.Unload();
}
}
}

Finally i got my solution, actually it recognize correctly, i'm handling them wrong way...

Related

Apache POI Mixed word format not working properly

FileInputStream fileInputStream = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fileInputStream);
for (XWPFParagraph p : document.getParagraphs()) {
Boolean isPrg=true;
XmlCursor cursor = p.getCTP().newCursor();
cursor.selectPath(
"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:txbxContent/w:p/w:r");
List<XmlObject> ctrsintxtbx = new ArrayList<XmlObject>();
while (cursor.hasNextSelection()) {
cursor.toNextSelection();
XmlObject obj = cursor.getObject();
ctrsintxtbx.add(obj);
}
for (XmlObject obj : ctrsintxtbx) {
CTR ctr = CTR.Factory.parse(obj.newInputStream());
XWPFRun bufferrun = new XWPFRun(ctr, (IRunBody) p);
String text = bufferrun.getText(0);
if (text != null && text != "") {
isPrg= false;
text = text.replace("[RECEPIENT_NAME]", name).replace("[ADDRESS1]", address1).replace("LETTER_GEN_DT", date)
.replace("[ID]",sbsbid).replace("MEMR_RX_ID", memrid)
.replace("MEMR_MCTR_RX_GROUP", memrgroup).replace("MEMR_MCTR_RXBIN", memrrxbin)
.replace("MEMR_MCTR_PCN", memrpcn);
System.out.println("header line is "+ text);
if((address2 == null || address2.equals("")) && (address3 == null || address3.equals(""))) {
text = text.replace("[ADDRESS2]",city+", "+state+" "+zip).replace("[ADDRESS3]","").replace("[ZIP]", "").replace("[CITY]", "").replace("[STATE]", "");
}
else if((address2 != null && !address2.equals("")) && (address3 == null || address3.equals(""))) {
text = text.replace("[ADDRESS2]",address2).replace("[ADDRESS3]",city+", "+state+" "+zip).replace("[ZIP]", "").replace("[CITY]", "").replace("[STATE]", "");
}
else if((address2 == null || address2.equals("")) && (address3 != null && !address3.equals(""))) {
text = text.replace("[ADDRESS2]",address3).replace("[ADDRESS3]",city+", "+state+" "+zip).replace("[ZIP]", "").replace("[CITY]", "").replace("[STATE]", "");
}
else if((address2 != null && !address2.equals("")) && (address3 != null && !address3.equals(""))) {
text = text.replace("[ADDRESS2]",address2).replace("[ADDRESS3]",address3).replace("[ZIP]",zip).replace("[CITY]", city).replace("[STATE]", state);
}
bufferrun.setText(text,0);
}
obj.set(bufferrun.getCTR());
}
if(isPrg) {
String runTxt="";
p.getCTP().documentProperties();
for(int i = 0; i < p.getRuns().size(); i++)
{
runTxt=runTxt+ p.getRuns().get(i);
}
System.out.println("main footer is :"+runTxt);
runTxt=runTxt.replace("[RECEPIENT_NAME]", name).replace("[PDP_NAME]", pdpname)
.replace("[ENRL_EFF_DT]", enrolldate).replace("[GLBL_PHONE_NUMBER]", phoneNumber);
int psize= p.getRuns().size();
if(psize>1) {
for(int i = 0; i < psize-1; i++)
{
try
{
p.removeRun(psize - i - 1);
}
catch(Exception e)
{
//e.printStackTrace();
}
}
}
for(XWPFRun ffr:p.getRuns()) {
ffr.setText(runTxt,0);
break;
}
}
}
outFilePath = filePath.replace(".docx", "_convert.docx");
FileOutputStream out = new FileOutputStream(
new File(outFilePath));
document.write(out);
out.close();
System.out.println("Output.docx written successully");
} catch (IOException | SQLException e) {
System.out.println("We had an error while reading the Word Doc");
}
return outFilePath;
}
Input Text :
will automatically terminate without notice when the base Contract terminates for any reason
Output i am getting like this:
will automatically terminate without notice when the base Contract terminates for any reason
For output also i need Bold text format after replacing the words in documents
Expected Output is :
will automatically terminate without notice when the base Contract terminates for any reason

Error: A JNI error has occurred (javax.mail.jar)

I'm trying to read gmail messages using showmsg.java in the javamail sample package, and I keep getting this error when I run it. The program compiles fine though.
Here's the error message:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/internet/ParseException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: javax.mail.internet.ParseException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Here's the code:
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
/*
* Demo app that exercises the Message interfaces.
* Show information about and contents of messages.
*
* #author John Mani
* #author Bill Shannon
*/
public class msgshow {
static String protocol;
static String host = null;
static String user = null;
static String password = null;
static String mbox = null;
static String url = null;
static int port = -1;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = false;
static boolean showMessage = false;
static boolean showAlert = false;
static boolean saveAttachments = false;
static int attnum = 1;
public static void main(String argv[]) {
int optind;
InputStream msgStream = System.in;
for (optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-v")) {
verbose = true;
} else if (argv[optind].equals("-D")) {
debug = true;
} else if (argv[optind].equals("-f")) {
mbox = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-p")) {
port = Integer.parseInt(argv[++optind]);
} else if (argv[optind].equals("-s")) {
showStructure = true;
} else if (argv[optind].equals("-S")) {
saveAttachments = true;
} else if (argv[optind].equals("-m")) {
showMessage = true;
} else if (argv[optind].equals("-a")) {
showAlert = true;
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println(
"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
System.out.println(
"\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
System.out.println(
"or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
System.exit(1);
} else {
break;
}
}
try {
// Get a Properties object
Properties props = System.getProperties();
// Get a Session object
Session session = Session.getInstance(props, null);
session.setDebug(debug);
if (showMessage) {
MimeMessage msg;
if (mbox != null)
msg = new MimeMessage(session,
new BufferedInputStream(new FileInputStream(mbox)));
else
msg = new MimeMessage(session, msgStream);
dumpPart(msg);
System.exit(0);
}
// Get a Store object
Store store = null;
if (url != null) {
URLName urln = new URLName(url);
store = session.getStore(urln);
if (showAlert) {
store.addStoreListener(new StoreListener() {
public void notification(StoreEvent e) {
String s;
if (e.getMessageType() == StoreEvent.ALERT)
s = "ALERT: ";
else
s = "NOTICE: ";
System.out.println(s + e.getMessage());
}
});
}
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();
// Connect
if (host != null || user != null || password != null)
store.connect(host, port, user, password);
else
store.connect();
}
// Open the Folder
Folder folder = store.getDefaultFolder();
if (folder == null) {
System.out.println("No default folder");
System.exit(1);
}
if (mbox == null)
mbox = "INBOX";
folder = folder.getFolder(mbox);
if (folder == null) {
System.out.println("Invalid folder");
System.exit(1);
}
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
int totalMessages = folder.getMessageCount();
if (totalMessages == 0) {
System.out.println("Empty folder");
folder.close(false);
store.close();
System.exit(1);
}
if (verbose) {
int newMessages = folder.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
}
if (optind >= argv.length) {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
// dumpPart(msgs[i]);
}
} else {
while (optind < argv.length) {
int msgnum = Integer.parseInt(argv[optind++]);
System.out.println("Getting message number: " + msgnum);
Message m = null;
try {
m = folder.getMessage(msgnum);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
}
}
}
folder.close(false);
store.close();
} catch (Exception ex) {
System.out.println("Oops, got exception! " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
/** Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.out.write(c);
**/
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}
String filename = p.getFileName();
if (filename != null)
pr("FILENAME: " + filename);
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure && !saveAttachments)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
} else {
if (!showStructure && !saveAttachments) {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
} else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
}
} else {
// just a separator
pr("---------------------------");
}
}
/*
* If we're saving attachments, write out anything that
* looks like an attachment into an appropriately named
* file. Don't overwrite existing files to prevent
* mistakes.
*/
if (saveAttachments && level != 0 && p instanceof MimeBodyPart &&
!p.isMimeType("multipart/*")) {
String disp = p.getDisposition();
// many mailers don't include a Content-Disposition
if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
if (filename == null)
filename = "Attachment" + attnum++;
pr("Saving attachment to file " + filename);
try {
File f = new File(filename);
if (f.exists())
// XXX - could try a series of names
throw new IOException("file exists");
((MimeBodyPart)p).saveFile(f);
} catch (IOException ex) {
pr("Failed to save attachment: " + ex);
}
pr("---------------------------");
}
}
}
public static void dumpEnvelope(Message m) throws Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
}
// REPLY TO
if ((a = m.getReplyTo()) != null) {
for (int j = 0; j < a.length; j++)
pr("REPLY TO: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
InternetAddress ia = (InternetAddress)a[j];
if (ia.isGroup()) {
InternetAddress[] aa = ia.getGroup(false);
for (int k = 0; k < aa.length; k++)
pr(" GROUP: " + aa[k].toString());
}
}
}
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for (int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
}
String[] uf = flags.getUserFlags(); // get the user flag strings
for (int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
}
pr("FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader("X-Mailer");
if (hdrs != null)
pr("X-Mailer: " + hdrs[0]);
else
pr("X-Mailer NOT available");
}
static String indentStr = " ";
static int level = 0;
/**
* Print a, possibly indented, string.
*/
public static void pr(String s) {
if (showStructure)
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
}
The command I'm using to run is java msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS] and the command I'm using to compile it is javac -cp ".:./:./lib:./lib/*" msgshow.java. The javax.mail.jar is contained in the lib folder
This is some alternate code that's much shorter and gets the same errors:
import java.util.*;
import java.io.*;
import javax.mail.*;
import smtp;
import imaps;
//import java.mail.*;
//import com.sun.mail.*;
public class AccessGmail {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
try
{
Properties prop = new Properties();
prop.load(new FileInputStream(new File("smtp.properties")));
Session session = Session.getDefaultInstance(prop, null);
String pass = scan.next();
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com","shane.l.gvoice#gmail.com",pass);
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
int messageCount = inbox.getMessageCount();
System.out.println("Message Count: "+messageCount);
}
catch (FileNotFoundException e){}
catch (IOException e){}
catch(NoSuchProviderException e){}
catch(MessagingException e){}
}
}
You're not setting the CLASSPATH when you're running the program so it's not finding the javax.mail.jar file:
java -cp ".:lib/javax.mail.jar" msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS]

How to fix input getting cut off by output

So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();

Displaying data from an ISP/Telephone (Telstra.com.au in Australia)

I am currently having issues in attempting to display data (i.e. itemSummaries with a certain ContainerType) for sites that are ISP, as an example, www.telstra.com.au from Australia
Logging into the site works fine, and the credentials for the site work fine (in other words, it does a refresh which succeeds), however there doesn't appear to be a way to display the itemSummary data
The soap command getItemSummaries, doesn't display data for the item (it displays item data from financial institutions fine). Upon examining the sample code provided by Yodlee for the java soap api, you are meant to use the getItemSummaries1 along with setting ContainerTypes using a SummaryRequest
The problem is that this returns a CoreExceptionFaultMessage. The getItemSummaries1 command is causing the CoreExceptionFaultError. Using different ContainerTypes with different combinations (i.e. ISP, Telephone, Bills) didn't alleviate the issue
The same error message is returned in Yodlees own sample code, i.e. java_soap_example (run the com.yodlee.sampleapps.accountsummary.DisplayBillsData main method and provide the Yodlee login info as command line arguments)
As a reference, the code that is provided by Yodlee sample app is below
Running the getItemSummaries1 command
public void displayBillsData (UserContext userContext)
{
/*SummaryRequest sr = new SummaryRequest(
new String[] {ContainerTypes.BILL, ContainerTypes.TELEPHONE},
new DataExtent[] { DataExtent.getDataExtentForAllLevels(),DataExtent.getDataExtentForAllLevels() }
);*/
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(new String[] {ContainerTypesHelper.BILL, ContainerTypesHelper.TELEPHONE});
sr.setContainerCriteria(list);
Object[] itemSummaries = null;
List itemSummariesList = null;
try {
itemSummariesList = dataService.getItemSummaries1(userContext, sr);
if (itemSummariesList != null){
itemSummaries = itemSummariesList.getElements();
}
} catch (StaleConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (InvalidConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (CoreExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentTypeExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentValueExceptionFault e) {
e.printStackTrace();
} catch (InvalidUserContextExceptionFault e) {
e.printStackTrace();
} catch (IllegalDataExtentExceptionFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if (itemSummaries == null || itemSummaries.length == 0) {
System.out.println ("No bills data available");
return;
}
for (int i = 0; i < itemSummaries.length; i++) {
ItemSummary is = (ItemSummary) itemSummaries[i];
displayBillsDataForItem(is);
// Dump the BillsData Object
// dumpBillsDataForItem(is);
}
}
Printing the item data
public void displayBillsDataForItem (ItemSummary is)
{
String containerType = is.getContentServiceInfo ().
getContainerInfo ().getContainerName ();
System.out.println("containerType = " + containerType );
if (!(containerType.equals(ContainerTypesHelper.BILL ) || containerType.equals(ContainerTypesHelper.TELEPHONE)
|| containerType.equals(ContainerTypesHelper.MINUTES))) {
throw new RuntimeException ("displayBillsDataForItem called with " +
"invalid container type: " + containerType);
}
DisplayItemInfo displayItemInfo = new DisplayItemInfo ();
System.out.println("DisplayItemInfo:");
displayItemInfo.displayItemSummaryInfo (is);
System.out.println("");
ItemData id = is.getItemData();
if(id == null){
System.out.println("ItemData == null");
}else{
List accountsList = id.getAccounts();
Object[] accounts = null;
if (accountsList != null){
accounts = accountsList.getElements();
}
if (accounts == null || accounts.length == 0) {
System.out.println ("\tNo accounts");
}else {
for (int accts = 0; accts < accounts.length; accts++) {
BillsData billsData = (BillsData) accounts[accts];
System.out.println("\tAccount Holder: " + billsData.getAccountHolder() );
System.out.println("\tAccount Id: " + billsData.getAccountId());
System.out.println("\tItemAccountId: " + billsData.getItemAccountId() );
System.out.println("\tAccountName: " + billsData.getAccountName() );
System.out.println("\tAccountNumber: " + billsData.getAccountNumber() );
System.out.println("");
// Get List of Bill Objects
List billsList = billsData.getBills();
Object[] bills = null;
if (billsList != null){
bills = billsList.getElements();
}
if (bills == null || bills.length == 0) {
System.out.println ("\t\tNo Bill objects");
}else {
for (int b = 0; b < bills.length; b++) {
Bill bill = (Bill) bills[b];
System.out.println("\t\tBill Account Number: " + bill.getAccountNumber() );
System.out.println("\t\tBill Acct Type: " + bill.getAcctType() );
System.out.println("\t\tBill Due Date: " + Formatter.formatDate(bill.getDueDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Date: " + Formatter.formatDate(bill.getBillDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Past Due: "
+ (bill.getPastDue() != null ? bill
.getPastDue().getAmount() : 0.0));
System.out
.println("\t\tBill Last payment: "
+ (bill.getLastPayment() != null ? bill
.getLastPayment()
.getAmount()
: 0.0));
System.out.println("\t\tBill Amount Due: "
+ (bill.getAmountDue() != null ? bill
.getAmountDue().getAmount() : 0.0));
System.out
.println("\t\tBill Min Payment: "
+ (bill.getMinPayment() != null ? bill
.getMinPayment()
.getAmount()
: 0.0));
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = bill.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\t\tNo AccountUsageData objects");
}else {
for (int usage = 0; usage < acctUsageData.length; usage++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usage];
System.out.println("\t\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = billsData.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\tNo AccountUsageData objects");
}else {
for (int usageData = 0; usageData < acctUsageData.length; usageData++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usageData];
System.out.println("\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
}
}
EDIT2:
I have updated the getItemSummaries1 command to look like this
ContainerCriteria bills = new ContainerCriteria();
ContainerCriteria telephone = new ContainerCriteria();
ContainerCriteria isp = new ContainerCriteria();
ContainerCriteria utilities = new ContainerCriteria();
bills.setContainerType(ContainerTypesHelper.BILL);
telephone.setContainerType(ContainerTypesHelper.TELEPHONE);
isp.setContainerType(ContainerTypesHelper.ISP);
utilities.setContainerType(ContainerTypesHelper.UTILITIES);
Object[] containerList = {
bills,telephone,isp,utilities
};
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(containerList);
sr.setContainerCriteria(list);
The command now executes and works correctly, however its returning a list of 0 elements (using DataExtents with different values didn't change anything). My suspicion is that Telstra.com.au site is broken on Yodlee's end (when a full refresh is done on the Telstra site, Yodlee returns a null for refreshing that specific site).
So far I can see some deviation, so do modify your container criteria as mentioned below
object[] list = {
new ContainerCriteria { containerType = "bills" },
new ContainerCriteria { containerType = "telephone" }
};
sr.containerCriteria = list;
You may additionally provide data extent as follows
DataExtent de = new DataExtent();
dataExtent.startLevel = 0; //as per your needs
dataExtent.endLevel = 0; //as per your needs
object[] list = {
new ContainerCriteria { containerType = "bills", dataExtent = de },
new ContainerCriteria { containerType = "telephone", dataExtent = de }
};
sr.containerCriteria = list;
This should solve your issue. If not then try to get the detail which is is node in the response for the CoreExceptionFaultMessage, this detail may help to diagnose the accurate issue.
To get data for any of the container first you need to add an account for the site belonging to that container. Once you have added the account successfully then only you will be able to pull in the data for such container. Also you can check the tag returned in the getItemSummaries API which has and once this statusCode = 0 then only you have data present for that account.
You can do testing by using the Dummy account which yodlee provides. Please refer to Yodlee Dummy account generator page for more info on Dummy accounts.

.dat file in java, how to access it, totally consfused on how to read in from it

So my problem is that, I want to input this list below in a .dat file and read it in but i dont know how, when i tried to do it via a .txt file (instead of .dat) and put it in the project order so i can have inputstream read through it gives me and excpetion
I dont mind using .txt but it gives me this streamcorrupted exception like below
java.io.StreamCorruptedException: invalid stream header: 4C696665
the list its supposed to reading
Life of Pi
Titanic
Tropic Thunder
GoodFellas
Momento
so what i want to do is put the list above in a inventory.dat file but i dont know how?
here is the code,
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static SortedList inventory;
static BufferedReader in;
public static StockItem getStockItem( String title2 )
{
int idx;
StockItem newItem = new StockItem( title2 );
//
// Determine whether the video with the title is in the inventory.
//
idx = inventory.locateIndex( newItem );
if ( idx <= inventory.size() )
{
StockItem oldItem = (StockItem)inventory.get( idx );
if ( oldItem.compareTo(newItem) == 0 )
return oldItem;
}
//
// If not, insert.
//
inventory.sortedAdd(newItem);
return newItem;
}
//
// If the stock item has no information, remove it from the inventory.
//
public static void VerifyStockItem( StockItem item )
{
if ( item.getHave() == 0 && item.getWant() == 0 &&
item.getWaitingList().isEmpty() )
{
inventory.sortedRemove( item );
}
}
public static void cmd_I( String title )
{
StockItem item = getStockItem( title );
System.out.println( item );
VerifyStockItem( item );
}
public static void cmd_L()
{
System.out.println( inventory );
}
public static void cmd_A( String title )
{
StockItem item = getStockItem( title );
System.out.println( "Input the initial want value:" );
while ( true )
{
try {
item.setWant( Integer.parseInt( in.readLine() ) );
break;
}
catch ( IOException e ) {
continue;
}
}
VerifyStockItem( item );
}
public static void cmd_M( String title )
{
StockItem item = getStockItem( title );
System.out.println( "The original want value was " + item.getWant() +
"." );
System.out.println( "Input the new want value:" );
while ( true )
{
try {
item.setWant( Integer.parseInt( in.readLine() ) );
break;
}
catch ( IOException e ) {
continue;
}
}
VerifyStockItem( item );
}
public static void cmd_D()
{
try {
BufferedReader fin =
new BufferedReader( new FileReader( "incoming.dat" ) );
int lines = Integer.parseInt( fin.readLine() );
for ( int i = 0; i < lines; i++ )
{
StringTokenizer st = new StringTokenizer( fin.readLine() );
String title = st.nextToken();
int count = Integer.parseInt( st.nextToken() );
StockItem item = getStockItem( title );
ListReferenceBased waitingList = item.getWaitingList();
System.out.println ( "Arrival: " + title + " x " + count );
while( count > 0 && !waitingList.isEmpty() )
{
Customer p = (Customer)waitingList.removeFirst();
System.out.println( "" + p + " received the video." );
count--;
}
if ( count > 0 ) {
item.setHave( item.getHave() + count );
}
VerifyStockItem( item );
}
}
catch( FileNotFoundException fnfe ) {
System.out.println( "incoming.dat should exist." );
return;
}
catch( IOException e ) {
System.out.println(
"The operation is aborted due to an IO error." );
}
}
public static void cmd_O()
{
Node iter = inventory.getHead();
while ( iter != null ) {
Node next = iter.getNext();
StockItem item = (StockItem)iter.getItem();
int count = item.getWant()
+ item.getWaitingList().size()
- item.getHave();
if ( count > 0 ) {
System.out.println( item.title + ": " + count );
}
iter = next;
}
}
public static void cmd_R()
{
Node iter = inventory.getHead();
while ( iter != null ) {
Node next = iter.getNext();
StockItem item = (StockItem)iter.getItem();
int count = item.getHave()
- item.getWant()
- item.getWaitingList().size();
if ( count > 0 ) {
System.out.println( item.title + ": " + count + " returned" );
item.setHave( item.getHave() - count );
}
VerifyStockItem( item );
iter = next;
}
}
public static void cmd_S( String title )
{
StockItem item = getStockItem( title );
if ( item.getHave() > 0 )
{
item.setHave( item.getHave() - 1 );
System.out.println( title + ": You took one. " +
item.getHave() + " video(s) left." );
}
else
{
System.out.println( title + " is sold out." );
System.out.println( "Write your name please." );
while (true) {
try {
Customer p = new Customer( in.readLine().trim() );
item.getWaitingList().addLast( p );
break;
}
catch( IOException e )
{
continue;
}
}
}
VerifyStockItem( item );
}
public static void main(String[] args)
{
//
// Loading from the inventory.dat
//
try {
FileInputStream fis = new
FileInputStream("inventory.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
inventory = (SortedList)o;
}
catch (FileNotFoundException fnfe) {
inventory = new SortedList();
}
catch (Exception e) {
System.out.println(e);
}
in = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String cmdLine;
char cmd;
String arg = "";
System.out.print( "Input a command: " );
try {
cmdLine = in.readLine();
}
catch(Exception e) {
break;
}
if (cmdLine.length() == 0) continue;
//
// parse the command line.
//
cmd = cmdLine.charAt(0);
if ( cmdLine.length() >= 3 ) arg = cmdLine.substring(2);
if ( cmd == 'Q' ) break;
//
// dispatch
//
switch( cmd )
{
case 'H':
System.out.println(
"Help on commands \n" +
"---------------- \n" +
"H (help) \n" +
"I <title> (inquire)\n" +
"L (list)\n" +
"A <title> (add)\n" +
"M <title> (modify)\n" +
"D (delivery)\n" +
"O (order)\n" +
"R (return)\n" +
"S <title> (sell)\n" +
"Q (quit)\n" );
break;
case 'I':
cmd_I( arg );
break;
case 'L':
cmd_L();
break;
case 'A':
cmd_A( arg );
break;
case 'M':
cmd_M( arg );
break;
case 'D':
cmd_D();
break;
case 'O':
cmd_O();
break;
case 'R':
cmd_R();
break;
case 'S':
cmd_S( arg );
break;
}
}
//
// Saving into the inventory.dat
//
try {
FileOutputStream fos = new
FileOutputStream("inventory.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(inventory);
fos.close();
// end try
}
catch (Exception e) {
System.out.println(e);
}
}
}
Well, your problem is that your are mixing Readers (plain text format) and Streams (binary format) in an inappropriate way.
First, you write an object in a file using a FileOutputStream. This save the file in binary format.
FileOutputStream fos = new
FileOutputStream("inventory.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(inventory);
fos.close();
Then, you try to do:
BufferedReader fin = new BufferedReader( new FileReader( "incoming.dat" ) );
int lines = Integer.parseInt( fin.readLine() );
But BufferedReader is made to read from plain text, and not from binary files. There is a special case to use it, that is with new BufferedReader(new InputStreamReader(System.in)). But this is because InputStreamReader transform from binary format (of command line) to plain text ;-)
Regards,
The ObjectInputStream constructor blocks until it completes reading
the serialization stream header. Code which waits for an
ObjectInputStream to be constructed before creating the corresponding
ObjectOutputStream for that stream will deadlock, since the
ObjectInputStream constructor will block until a header is written to
the stream, and the header will not be written to the stream until the
ObjectOutputStream constructor executes. This problem can be resolved
by creating the ObjectOutputStream before the ObjectInputStream, or
otherwise removing the timing dependency between completion of
ObjectInputStream construction and the creation of the
ObjectOutputStream.
javaspecs

Categories