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.
Related
Im trying to create an application that reads names from an input file and writes the number of duplicate names on an output file. Heres my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
public class GenerateDuplicateBookTitle {
public static void main(String[] args) {
// declare and intialize path where the input file is stored
String filePath = "C:/Users/User/OneDrive/Desktop/JavaProgram";
// intialize input file name and output file name
String inputFile = "bookTitles.inp";
String ouputFile = "duplicateTitles.inp";
// create HashSet which does not store duplicate values
HashSet<String> bookTitles = new HashSet<>();
// create arrayList which stores only duplicate bok titles
ArrayList<String> duplicateBookTitles = new ArrayList<>();
// now read the book titles from the bookTitles.inp
try{
// create an object Of fileReader class with the specified filename with the path
FileReader fr = new FileReader(filePath+inputFile);
// create an object of BufferedReader class for reading line from inp file
BufferedReader br = new BufferedReader(fr);
String getLine = "";
System.out.println("-------------- Fetch data from the file ---------------\n");
while((getLine = br.readLine()) != null){
// add book title to the bookTitles arrayList
if(!bookTitles.contains(getLine)){
// diplay to the console
System.out.println(getLine+" read successfully from "+filePath+inputFile);
// add to the hash set
bookTitles.add(getLine);
}else{
duplicateBookTitles.add(getLine);
}
}
// display duplicate book title into the console
System.out.print("Duplicate book titles fetched from "+filePath+inputFile+" : ");
System.out.println(duplicateBookTitles.toString());
// now store it into the "duplicateTitles.txt" file
// create an object of FIleWriter class for writing data into the txt file
FileWriter write = new FileWriter(filePath+ouputFile);
System.out.println("\n------------ Write Duplicate BookTitles ----------------\n");
// now get each element from the duplicateBookTitles arrayList
for(String duplicateBookTitle : duplicateBookTitles){
// write into the "duplicateTitles.txt" file
write.write(duplicateBookTitle+"\n");
// print on console
System.out.println(duplicateBookTitle+" write succssfully into the
"+filePath+ouputFile);
}
// close the writer
write.close();
fr.close();
br.close();
}catch(FileNotFoundException e){
System.out.println("FILE '"+inputFile+"' IS NOT FOUND in "+filePath);
} catch (IOException ex) {
System.out.println(ex);
}
}
I keep getting an error message that the input file can't be found even though I am typing in the exact address of the file. The file name and format are correct and its in the same folder as the BlueJ program. What am I doing wrong here?
You are concatenating the directory path and the filename without the "/". Change FileReader fr = new FileReader(filePath+inputFile); to:
FileReader fr = new FileReader(filePath + "/" + inputFile);
Alternatively, you can do:
FileReader fr = new FileReader(new File(filePath, inputFile));
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.
This is my current code:
import java.util.*;
import java.io.*;
public class Adding_Deleting_Car extends Admin_Menu {
public void delCar() throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
I would like to delete a certain line of text from a file based on user input. For instance, this is my text file:
AB234KXAZ;Honda;Accord;1999;10000;3000;G
AB234KL34;Honda;Civic;2009;15000;4000;R
CD555SA72;Toyota;Camry;2010;11000;7000;S
FF2HHKL94;BMW;535i;2011;12000;9000;W
XX55JKA31;Ford;F150;2015;50000;5000;B
I would like the user to input the String of their choice, this will will be the first field in the column (eg. XX55JKA31), and then have that line of text deleted from the file. I've found some code online, but I've been unable to use it successfully.
My current code seems to just rewrite everything in the temporary text file, but doesn't delete it.
You are using File.renameTo, which is documented here:
https://docs.oracle.com/javase/8/docs/api/java/io/File.html#renameTo-java.io.File-
According to the documentation, it may fail if the file already exists, and you should use Files.move instead.
Here is the equivalent code with Files.move:
boolean successful;
try {
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
successful = true;
} catch(IOException e) {
successful = false;
}
Note:
Your code which searches for the VIN is also wrong. See Jure Kolenko's answer for one possible solution to that issue.
Moving forward, you should consider using an actual database to store and manipulate this type of information.
Your error lies in the
if(trimmedLine.equals(lineToRemove)) continue;
It compares the whole line to the VIN you want to remove instead of just the first part. Change that into
if(trimmedLine.startsWith(lineToRemove)) continue;
and it works. If you want to compare to a different column use String::contains instead. Also like Patrick Parker said, using Files.move instead of File::renameTo fixes the renaming problem.
Full fixed code:
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Adding_Deleting_Car{
public static void main(String... args) throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
Note that I changed the class definition not to inherit and the method definition to main(String... args), so I could compile on my system.
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();