Simple file read write code won't work - java

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.

Related

JAVA OCR to txt file

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.

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

User input into a text file in java

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.

File doesn't exist but says it does?

Alot of people have the problem "Says File doesn't exist, but it does" but my problem is the opposite, the file doesn't exist but it says it does.
Unsure on how to solve this problem and other topics just come up with "File doesn't exist but it does", etc.
Here's my code:
package New;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileEditor {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Where is the file stored ex: C:/Users/Name/Place/filename.txt");
String a = scan.nextLine();
File file = new File(a);
FileWriter writer = new FileWriter(file);
BufferedWriter bwriter = new BufferedWriter(writer);
if(!file.exists()){
System.out.println("File does not exist.");
}
else{
System.out.println("Start editing? y/n");
String b = scan.nextLine();
Don't create the FileWriter/BufferedWriter until AFTER you verify the file exists.
The file does exist. You're creating it right before you check whether it exists:
FileWriter writer = new FileWriter(file);

Not creating file (Java)

For some reason I keep on getting the following error when I compile my code. I have the correct preprocessor directives (import statements), and no syntax errors but whenever I compile my code I am given
probably,your dateFile is empty which might be the reason for this exception
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt()
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
refer http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = new File("test.txt");
FileWriter fw = new FileWriter(dateFile);
BufferedWriter bw = new BufferedWriter(fw);
Scanner reader = new Scanner(dateFile);
try
{
// if file doesnt exists, then create it
if (!dateFile.exists())
{
dateFile.createNewFile();
bw.write("1");
bw.close();
System.out.println("Done");
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
bw.write(""+duration);
bw.flush();
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File(""+fileName+".txt");
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
fw = new FileWriter(newSession.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Now it should work.
I add this two lines:
bw.write(""+duration);
bw.flush();
you were never write in the File.
Remember to .flush() your buffer.. if you want it to write on the file before you close it!
notice that i changed the path of the file to let it work on my pc so change it again

Categories