Good afternoon people,
With the help of research I did the code below to read texts of images:
package pckLeitor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Tess4jOCRv2 {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try
{
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
String fileExit = "C:\\Users\\RAFSOUZA\\Desktop\\OCRTest" + dtNow + ".txt";
FileWriter fstream = new FileWriter(fileExit);
BufferedWriter out = new BufferedWriter(fstream);
out.write(fullText);
out.newLine();
out.close();
}
}
catch (Exception e)
{
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
I would like to improve this code for:
1) Read all images in a folder
2) Generate a txt file with the data read from each image
Can you give me a direction?
Okay, so you've already gotten the code to read an image and output all text, right?
Let's try and wrap that with a loop or something using File#listFiles() and we should be ok!
Something like this should work, note I wrote this in notepad and it has not been tested!
import java.io.File;
public class Tess4jOCR {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try {
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
//String file = "O:\\Operações\\MIS\\Csa_OCR" + dtNow + ".txt";
String file = "C:\\RegistroRS" + dtNow + ".txt";
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//System.out.println(fullText);
out.write(fullText);
out.newLine();
out.close();
}
} catch (Exception e) {
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
Simply put all images you want to process in C:\\Users\\RAFSOUZA\\Desktop\\OCRTest (or whatever directory the repository variable is set to, and run it and it should output it to C:\\RegistroRS-<timestamp>.txt
Please note you may want to add additional logic to check filenames or maybe output the txt file in a name that's related to the original input so you don't reprocess things if you run the code more than once and you can easily tell which output came from which input.
Related
I want a user to be able to copy and paste multi-line text into the console and then save it to a specific text file ("weather.text" in this case which is located in a data folder within the same package). I've been working on this simple task for a few hours and the solution is evading me. I'm new to java so I apologize in advance.
This static function is called from the main launcher class.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Scanner;
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
str = br.readLine();
//save the user input data to text file
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
writer.print(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
currently I'm experiencing 2 problems.
1) The code above seems to only save the first line pasted into the console into the console.
2) The text file being saved is in the global project folder and not the specified data sub folder.
Any help or suggestions are appreciated. Thank you.
You are writing str, but str is just the first line in br You have to read all lines in a loop.
Try this code:
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
while((str = br.readLine())!=null)
{
//save the line
writer.println(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
about the second issue, the file is written in the working directory of your application.
I have created a simple file read and write program. When compiling, the program shows no errors and runs without problem, but when I try to open the output file, I get a "file corrupted" error, and the size of the file is 0kb.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Extention
{
FileInputStream filein;
FileOutputStream fileout;
void asdf() throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.print("/**");
System.out.print("\n");
System.out.print("* Created by Arul on 6/15/2016 *");
System.out.print("\n");
System.out.print("**/");
System.out.print("\n");
try {
System.out.print("Enter Name of the file to read : ");
filein = new FileInputStream(br.readLine());
System.out.print("Enter Name of the file to write : ");
fileout = new FileOutputStream(br.readLine());
int i;
do {
i = filein.read();
if (i == -1)
break;
fileout.write(i);
} while (i != -1);
} catch (FileNotFoundException f) {
System.out.println("Exception : File not found!");
} finally {
filein.close();
fileout.close();
}
}
public static void main(String arg[]) throws IOException
{
Extention d = new Extention();
d.asdf();
}
}
When you say, "File corrupted", is this a Java error which you get during execution of your program, or is this an error when you double click on the created file?
If it's the latter, it all depends on what you are trying to copy. If you used it to copy an TXT file, but you changed the file ending to MP3, you would find that, when you double click on the file, your media player will be selected to open the text file and won't understand the text data.
I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system.
Input from file Code:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
Output to File
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
For reading text from a file
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
For Writting Text to file
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();
This is my code:
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class Append
{
public static void main( String[] args )
{
try{
String data = " Thank you very much";
File file =new File(" ");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
System.out.println("New File Created Now");
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
In above code i am trying to add "String data = " Thanks you very much"; " in G://Openone.txt, but its not wokrking correctly, and i am not getting the output.
public static void main( String[] args )
{
try{
String data = " Thank you very much";
File file =new File(" ");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
System.out.println("New File Created Now");
}
//true = append file
FileWriter fileWritter = new FileWriter(file,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
fileWritter.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}
Use file object instead of file.getName() in following line.
FileWriter fileWritter = new FileWriter(file.getName(),true);
File file =new File(" ");
should become
File file = new File("G:\\Openone.txt");
If you are using Java 7+, you can use:
Files.write(Paths.get("G:\\Openone.txt"), "Thank you very much".getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
BTW, I recommend you to refactor your code in order to manage the exception properly with a finally block, because if an exception is throw in write line the close method will not be called.
I have ran into a problem with my program. The bellow method is the part of my program that is suppose to store the text lines stored in ArrayList into a text file (e.g store.txt) what am I doing wrong here? The program compiles but it does not store the text lines in to the said file. Bellow is the said method that is suppose to store the text lines
// this part stores the string into a file
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(
"C:/Users/Asus/Desktop/zing/store.txt/" + fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
Try this. It's runnable code. It shows the code you have above works fine. I just changed the file path. I'm running from NetBeans so the file ends up in the Project Root folder.
ProjectRoot
src
build
store.txt
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class StoreToFIle {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add(String.valueOf(i));
}
storeTextLinesToFile(list, "store.txt");
}
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
}
Use printStackTrace() in catch block. Then only you know the absolute error of your program.
and look here.
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/store.txt/" + given_file_name ) ) ;
Suppose store.txt is a file instead of directory, then you will get FileNotFoundException.
So try like this..
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/" + given_file_name ) ) ;
Give value to given_file_name as "store.txt"