I'm trying to use Tesseract OCR in a web application. The code runs fine when I run it as a JAVA application. But as soon as I put the same code in my web application, it doesn't work anymore. If put the function in the servlet, tomcat doesnt start at all. If I call it from a separate class by creating an object, On debugging I find that the object does not get created at all. I have included all the jars necessary.
Code in servlet
OCRFullTrial ot = new OCRFullTrial();
ot.imgOCR();
Inside other class
public void imgOCR(){
File imageFile = new File("D:\\OCRTesting\\0.jpg");
try {
ITesseract instance = new Tesseract(); //
System.out.println("1");
} catch (Exception e) {
System.err.println(e.getMessage());
}
Just some pointers I think you should check, in case if you are using Tess4j in Web Based Project:
1) Put all your jars in WEB-INF > lib folder.
2) The *.dll files that are provided along Tess4j must be in system32 folder (Windows). I don't know for other OS.
3) Set the instance path using instance.setDataPath() method. It must point to folder containing tessdata folder.
4) Set the language using instance.setLanguage() incase your tessdata has multiple languages training data in them.
Crosscheck above steps and try running again. Hope it works
Related
When someone opens my jar up I am opening a file selector gui so they can choose where they want to store their jar's files like config files and such. This should only take place the first time they open the jar. However, one issue with this approach is that I would have no way to know if it's their first time opening the jar since I will need to save the selected path somewhere. The best solution to this sounds like saving the selected path inside a file in the resource folder which is what I am having issues with. Reading and writing to this resource file will only need to be done when the program is actually running. These read and write operations need to work for packaged jar files (I use maven) and in the IDE.
I am able to read a resources file inside of the IDE and then save that file to the designated location specified in the file selector by doing this. However, I have not been able to do the same from a jar despite trying multiple other approaches from other threads.
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("config.yml");
try {
if(is != null) {
Files.copy(is, testFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
So just to clarify when my project is loaded I need to listen for the user to select a valid path for files like my config. Then I want to write my config to that path which I can do from my IDE and is shown above but I cant figure this out when I compile my project into a jar file since I always receive a file not found error in my cmd. However, the main point of this post is so that I can figure out how to save that selected path to my resource folder to a file (it can be json, yml or whatever u like). In the code above I was able to read a file but I have no idea how to go from that to get the files path since then reading and writing to it would be trivial. Also keep in mind I need to be able to read and write to a resource folder from both my IDE and from a compiled jar.
The following code shows my attempt at reading a resource from a compiled jar. When I added a print statement above name.startWith(path) I generated a massive list of classes that reference config.yml but I am not sure which one I need. I assume it has to be one of the paths relating to my project or possible the META-INF or META-INF/MANIFEST.MF path. Either way how am I able to copy the file or copy the contents of the file?
final String path = "resources/config.yml";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
if(jarFile.isFile()) { // Run with JAR file
try {
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith(path)) { //filter according to the path
System.out.println(name);
}
}
jar.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
Also if you were wondering I got the above code from the following post and my first block of code I pasted above is actually in the else statement since the IDE code from that post also did not work.
How can I access a folder inside of a resource folder from inside my jar File?
You can't write to files inside your JAR file, because they aren't actually files, they are ZIP entries.
The easiest way to store configuration for a Java application is to use Preferences:
Preferences prefs = Preferences.userNodeForPackage(MyApp.class);
Now all you have to do is use any of the get methods to read, and put methods to write.
There is absolutely no need to write files into your resource folder inside a jar. All you need to have is a smart classloader structure. Either there is a classloader that allows changing jars (how difficult is that to implement?), or you just setup a classpath that contains an empty directory before listing all the involved jars.
As soon as you want to change a resource, just store a file in that directory. When loading the resource next time, it will be searched on the classpath and the first match is returned - in that case your changed file.
Now it could be that your application needs to be started with that modified classpath, and on top of that it needs to be aware which directory was placed first. You could still setup that classloader structure within a launcher application, which then transfers control to the real application loaded via the newly defined classloader.
You could also check on application startup whether a directory such as ${user.home}/${application_name}/data exists.
If not, create it by extracting a predefined zip into this location.
Then just run your application which would load/write all the data in this directory.
No need to read/write to the classpath. No need to include 3rd party APIs. And modifying this initial data set would just mean to distribute a new zip to be extracted from.
I want to understand the best or the standard technique to write a java project when using internal files. To be precise, I want to develop a project that uses text files and images that are needed when the program runs. My goal is to create a runnable jar from the project in which the user does not need to see all these files. Therefore, I decided to create a package called resources and put it inside the folder that contains the source codes. I.e. it is in the same level as other packages. Now, in my codes when I want to use the images I use the following statement:
URL url = getClass().getResource("/resources/image1.gif");
It is working!
Then, to open a text file for reading/writing, I use the following:
String filename= "/resources/"+file1.txt;
Now, this is not working and it complains that it cannot find the file. I am not sure how to go about this?
A google search suggested that I put the resources folder on the project root directory. It is working then but when I created the runnable jar I had to put the resources folder on the same directory as the jar. This means that the user can have access to all the files in there. Any help is much appreciated.
You can use the getResource method for files too.
URL url = getClass().getResource("/resources/file1.txt");
try {
File f = new File(fileUrl.toURI());
} catch (URISyntaxException e) {
//dealing with the exception
}
I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds
I have a JFrame window that downloads a jar file & then starts it so the jar will execute inside the JFrame and show inside it too.
But the whole idea is, instead of letting users download the new jar version it will automatically grab (download) the new jar with the same launcher.
Now I don't want to let them download it many times everytime, might cause bandwidth lose etc, and instead I thought of having version checking.
Java will first check if the folder MyJar exists at the home folder of the OS, along with the jar file, if yes it will access the jar files data and check if the string version equals to the new version that I will buffer before it from the website, if not equal, download a new jar file into that folder. and then start it.
if jar version equals it will process and launch that jar.
This is the code I use currently to load form the web:
String jarURL = "http://someurl/game.jar"; // example broke the link from stackoverflow
String mainClass = "main";
ClassLoader clientClassLoader = new URLClassLoader(
new URL[] { new URL(jarURL) });
Class<?> clientClass = clientClassLoader.loadClass(mainClass);
this.loader = (Applet) clientClass.newInstance();
And I want to do something like this, for example in that jar I have a public variable named version, so I can access this.loader.getClass(main.class).version <- I know it's not done that way but just an example.
How can I do this?
I am making an java application which reads a file from a particular location. The location of the file is in the folder retrived from
getCanonicalPath().
The problem i am facing is that when i am running my application in Eclipse the canonical path is different from the one which Dr Java sees. So, what should i do before delivering my application to the client to make sure that it sees the file no matter which ide/command prompt is used to run the application. Obviously it would not be a good idea to copy the same file across all possible folders to cover different possibilities of getCanonicalPath.
Thanks
One of the solution is to have this file in your classpath and load it from your classpath, with a code like
URL url = getClass().getClassLoader().getResource(path);
if(url != null) {
try {
return new File(url.toURI().getPath());
} catch (URISyntaxException e) {
return null;
}
}
This is standard if this file is a configuration file. Usually in a standard java project layout you put this in the folder src/main/resources.
If this is more of a data file, you should put in a configuration file its path, and have different configurations, one for your station and one for production on the client machine. Of course in this case the configuration file is in the class path ;).
A common solution is to place the file in a directory which is in the class path. If you use getResource or getResourceAsInputStream you can find the file regardless of where it is provided its in the class path. if you use maven you can be sure how the classpath is setup regardless of the IDE used.
You should always load file ClassLoader using API like Test.class.getClassLoader().getResource(name),Test.class.getClassLoader().getResourceAsStream(name) More Information available here