Tess4J: The result String can't be parsed to int - java

I'm scanning single letters and numbers. All the numbers should be parsed into numbers[]. But it's always catching the exception. For Example: result is "3" but I can't parse it for some reason. I also tried to check if it's actually "3" with an if statement but I also got a false returned. Can someone explain me why it isn't working?
File imageFile = new File("C:\\Users\\Nils\\IdeaProjects\\untitled8\\Images\\Cutted\\"+i+m+".png");
ITesseract instance = new Tesseract(); // JNA Interface Mapping
// ITesseract instance = new Tesseract1(); // JNA Direct Mapping
instance.setDatapath("C:/Users/Nils/Desktop/blum/Tess4J/tessdata"); // path to tessdata directory
try {
String result = instance.doOCR(imageFile);
try {
resultI=Integer.parseInt(result);
numbers[0] = resultI;
}catch (NumberFormatException e){
numbers[0]=0;
}
} catch (TesseractException e) {
System.err.println(e.getMessage());
}

Ok I figured it out.
if(result.length()>1)
result=result.substring(0,1);
Delets everything that caused errors but keeps the number I want to separate.

Related

Accessing the output of a command running in a docker container

I'm trying to upgrade from docker-java 0.10.3 to 3.2.7. This line has me completely stumped:
InputStream response =
dockerClient.attachContainerCmd(container.getId())
.withLogs(true)
.withStdErr(true)
.withStdOut(true)
.withFollowStream(true)
.exec();
I have managed to get round one error by changing it to
InputStream response =
dockerClient.attachContainerCmd(container.getId())
.withLogs(true)
.withStdErr(true)
.withStdOut(true)
.withFollowStream(true)
.exec(new AttachContainerResultCallback());
(but my IDE says that AttachContainerResultCallback is deprecated.) The problem is that .exec() used to return an InputStream. Now it returns a void. I need the InputStream, because the output of the commands running in the container needs to find it's way to the screen. This needs to be realtime, because the user needs to see the output of the commands as they are running; I can't just copy a file at the end.
How can I get hold of this InputStream?
The error is:
java: incompatible types: inference variable T has incompatible bounds
lower bounds: java.io.InputStream,com.github.dockerjava.api.async.ResultCallback<com.github.dockerjava.api.model.Frame>
lower bounds: com.github.dockerjava.core.command.AttachContainerResultCallback
Try it:
var outputStream = new PipedOutputStream();
var inputStream = new PipedInputStream(outputStream);
var response =
dockerClient.attachContainerCmd(container.getId())
.withLogs(false)
.withStdErr(true)
.withStdOut(true)
.withFollowStream(true)
.exec(new ResultCallback.Adapter<>() {
#Override
public void onNext(Frame object) {
System.out.println(object); //for example
try {
outputStream.write(object.getPayload());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
try {
response.awaitCompletion();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Variable inputStream will be what you are looking for.
P.S. In my case I do withLogs(false) because it blocks the current output and I get only part of the log. It probably has something to do with the container I'm connecting to.

Reading from csv file give NumberFormatException?

I am reading datas from a csv file and set all datas into an object.At a particular point i am getting a numberformat exception (only after reading some datas)because some datas are not numbers(That is an error inside file some charecter datas in place of numerical datas,not able to use string concept because of some integration issues with main program).At that point i need to skip that line and need to move to the nextline.Can anyone please help.Any help will be highly appreciable.
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
encap.setPrice((nextLine[5]));
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Note:I need to skip and read next line onwards when ever numberformat exception occurs for a particular line.(value is getting correctly but my program stops whenever a numberformat exception occurs.......
encap is the object of my class....
Expand the scope of your try catch. Brute force, put try just below while and include ALL code in that while block inside that try block.
It looks like your try..catch is already in the right place. Just make a new encap for each record and it should behave as you want:
List<Encap> encaps = new ArrayList<Encap>(); // <- create list of results
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
Encap encap = new Encap(); // <- create a new instance for this line
encap.setPrice(nextLine[5]);
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
encaps.add(encap); // <- add this result to the list only if parsed ok
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

FileNotFoundException being thrown while file is present. File name might contain special characters

I wonder if anyone knows why I may be getting a java.io.FileNotFoundException when I'm trying to find a file that I know exists in the directory.
I think the following have something to do with it, please let me know if I'm correct or if there's something else:
I downgraded my JVM from 1.7 to 1.6
The file name contains two question marks, so the file is called filename_?)?.data
While I was using JVM 1.7, the program was able to find the file and open it. However, after downgrading to 1.6, it looks like it can't find this particular file. So I'm thinking maybe JVM 1.6 can't read files w/ question marks in them.
Also, I double/triple checked and the file does exist in the directory my program is looking in (its able to find other files in there as well).
Here's my code below:
public Object readFromFile(String fileName) {
// Check for null
if (fileName == null || fileName.equals("")) return null;
Object obj = null;
ObjectInputStream input = null;
// Open file into (input)
try {
input = new ObjectInputStream(new FileInputStream(fileName + ".data"));
} catch (IOException e) {
e.printStackTrace();
}
// Read content of file into (obj)
try {
obj = input.readObject();
input.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
probably you need to encode your filename when it is using special chars
Try this
String fileNameNew= java.net.URLEncoder.encode(fileName);
if (fileNameNew == null || fileNameNew.equals("")) return null;
Object obj = null;
ObjectInputStream input = null;
...
and you might check here: How to determine if a String contains invalid encoded characters

Strange input error, I have used this code before

After a very bad attempt at doing my homework, I decided it would be faster to abandon everything and start from scratch. Well not everything ... I copied this part since it worked perfectly so I saw no need to modify it. While maybe not perfect, it worked.
However now, when I compile just to test it out, I get an unexpected error:
Input error: java.io.EOFException.
Notice that "Input error" is from my catch(IOException ioe).
The file (fileName) is completely empty. Nothing in it. What could cause this. Is there a way to tell the ObjectInputStream to do nothing if the file is empty ?
Also I tested this out with an empty file on my other "iteration", didn't have this problem. I even named my file the same.
public Repository (String fileName) throws FileNotFoundException,
IOException,
SecurityException,
ClassNotFoundException {
this.fileName = fileName;
this.clients = new ArrayList<Client> ();
FileInputStream fileIn = null;
ObjectInputStream in = null;
try {
fileIn = new FileInputStream(this.fileName);
in = new ObjectInputStream(fileIn);
this.clients = (ArrayList<Client>) in.readObject();
} catch (FileNotFoundException fnfe) {
System.out.println("File not found, error: " + fnfe);
} catch (IOException ioe) {
System.out.println("Input error: " + ioe);
} catch (ClassNotFoundException cnfe) {
System.out.println("Class not found, error: " + cnfe);
} catch (SecurityException se) {
System.out.println(
"You do not have permission to access this file, error: "
+ se);
} finally {
if (fileIn != null)
fileIn.close();
if (in != null)
in.close();
}
Surely before
in = new ObjectInputStream(fileIn);
this.clients = (ArrayList<Client>) in.readObject();
you want to check the file size via File.length().
I assume if it's empty then you'd want to return an empty array list. You can't do that via deserialising an empty file. After all, even an empty array list has a non-zero size (and would need to identify itself as an array list via serialised attributes)
The file (fileName) is completely empty. Nothing in it.
That's exactly the problem. You cannot read an object (or an array) from an empty file. It will not find any data and throw an End-of-file-Exception (EOFException).
Even an empty array - when serialized to a file - will produce some data because the object stream will write the type (ArrayList) and the size of the array (0) to the file. When you try to read it, it will expect to find this data.

How do I update a File created by openFileOutput

I'm currently building an application where the user will generate data over time and, should he/she has an internet connection, transmit it to the web. However, if he doesn't have web access, I need to store this data in the phone until the user recovers his access, when I'll need to recover this data to be transmitted. However, I'm facing lots of troubles to do this, as per below.
Note: before anything, I'm using a local java-created file because I know no other way to save/restore this data on the device. If you happen to know any other way to store/access this data from within the device please feel free to comment here.
Just for reference,
phantoms is an ArrayList containing objects with the data I need to
store,
Arquivador is the class that I'm using to make my data persistent and to recover it,
Funcionario is the class with the data generated by the program (just a few strings and numbers)
I am able to write a file to the file system through the code below, on my Activity:
try {
arq = new Arquivador();
arq.addFirstObjectInFile(
openFileOutput("dados.jlog", MODE_WORLD_WRITEABLE),
phantoms.get(0));
phantoms.remove(phantoms.get(0));
for (Funcionario func : phantoms) {
arq.addObjectInFile(openFileOutput("dados.jlog", MODE_APPEND),
func);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
}
Here is the code inside Arquivador that adds the data to a file:
public void addObjectInFile(FileOutputStream arquivo,
Object objetoAAdicionar) {
try {
ObjectOutputStream aoos = new ObjectOutputStream(arquivo);
aoos.writeObject(objetoAAdicionar);
aoos.close();
} catch (IOException ioe) {
Log.d(TAG_NAME, "Erro no Appendable OOS.");
}
}
public void addFirstObjectInFile(FileOutputStream arquivo,
Object objetoAAdicionar) {
try {
AppendableObjectOutputStream aoos = new AppendableObjectOutputStream(
arquivo);
aoos.writeObject(objetoAAdicionar);
aoos.close();
} catch (IOException ioe) {
Log.d(TAG_NAME, "Erro no Appendable OOS.");
}
}
You will notice that I'm adding data to persistence in 2 steps, the first Object and the rest of them. This was an idea I saw on this post, here in StackOverflow, to allow appending data to a Java generated file. I have no problem with this code, it works perfectly.
Later on, back on my Activity, the internet connection is detected and I try to recover the file saved on the disk:
phantoms = new ArrayList<Funcionario>();
Object obj = arq.readObjectFromFile(openFileInput("dados.jlog"));
Funcionario func = null;
if (obj instanceof Funcionario) {
func = (Funcionario) obj;
}
while (func != null) {
phantoms.add(func);
arq.removeObjectFromFile(openFileInput("dados.jlog"), func,
getApplicationContext());
func = (Funcionario) arq
.readObjectFromFile(openFileInput("dados.jlog"));
}
The original idea was to read 1 object at a time, then attempt to transmit it and, if successful, erase the object from the file (so it didn't get retransmitted). However, I was having too many error messages with this. Instead, I decided to load all the objects at once, one by one, to see where my problem was more clearly.
Back to the Arquivador class:
public Object readObjectFromFile(FileInputStream arquivo) {
Object retorno = null;
if (arquivo.equals(null)) {
Log.e(TAG_NAME, "FIS is null!");
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(arquivo);
retorno = ois.readObject();
} catch (IOException ioex) {
} catch (ClassNotFoundException e) {
} finally {
try {
if (ois != null) ois.close();
} catch (IOException e) {
}
}
return retorno;
}
public void removeObjectFromFile(FileInputStream arqPrincipal,
Object objetoARemover, Context contexto) {
try {
// Construct the new file that will later be renamed to the original
// filename.
ObjectOutputStream oos = new ObjectOutputStream(
contexto.openFileOutput("dados.jlog.temp",
contexto.MODE_APPEND));
ObjectInputStream ois = new ObjectInputStream(arqPrincipal);
Object obj = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
try {
while ((obj = ois.readObject()) != null) {
if (!(objetoARemover.equals(obj))) {
oos.writeObject(obj);
oos.flush();
}
}
} catch (EOFException eof) {
} finally {
oos.close();
ois.close();
// Delete the original file
File aDeletar = contexto.getFileStreamPath("dados.jlog");
File aRenomear = contexto.getFileStreamPath("dados.jlog.tmp");
if (!aDeletar.delete()) {
return;
} else {
// Rename the new file to the filename the original file
// had.
if (!aRenomear.renameTo(aDeletar)) Log.d(TAG_NAME,
"Error renaming file");
else Log.d(TAG_NAME, "Renaming successful");
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.d(TAG_NAME, "Arquivo não encontrado");
} catch (IOException ex) {
ex.printStackTrace();
Log.d(TAG_NAME, "Erro de entrada/saída");
} catch (ClassNotFoundException e) {
Log.d(TAG_NAME, "Classe Não Encontrada.");
}
}
The method readObjectFromFile() seems to work just fine. I can even convert the read Object to Funcionario class and read its data.
My problems appear when I use removeObjectFromFile(). The idea is to create a temporary file to store objects from "dados.jlog" file other than the one that has been already loaded in the main program, then once this temp file is created the file "dados.jlog" should be deleted and the temporary file should be renamed to replace it.
The first thing I found out to be strange here is that the ois.readobject() keeps throwing an EOFException. While this makes sense, the tutorial I read on the internet doesn't mention this error. In fact, their code indicates that when the readObject() method reaches the EOF, it would return a reference to null, but instead this class throws this EOFException. I handled this exception in the code - though I'm not sure if this would be the right way to do it.
Another thing I find strange is the fact that this code fails to recognize the object that it should NOT copy. When I compare the object read from the file to the one received as argument, no matter what I try ( == , equals(), etc) they seem different objects to the compiler. Funcionario class is serializable has a serialversionUID, so the object read from the file should be identical to the one I stored. Worse than this, these 2 Objects being compared are read from the same file. They should be identical, right?
After creating the temporary file, I try to delete the original file and rename the temporary file. Though this seems to be working, once the removeObjectFromFile() ends the first time, the program is unable to read the data from the file "dados.jlog" again. I can't read the remaining data from the file and the program enters on an endless loop - since the 1st object is never removed from the list in the file.
Please enlighten me with this matter.
Personally I'd use an SQLLite database. Store each object in a row in the database. Once you've successfully transmitted you can remove the row from the database.
You can even reuse most of your code that you've already done. The easiest way to get there from where you are is to use a separate file for each object and store only the filename of the object in the database. You can then iterate over the rows in the database. Each time you transmit an object to your server simply delete that row from the database (and remove the file from the filesystem!). No rows in the database means no objects remain to be transmitted.

Categories