reading/writing variables from text files to variables - java

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();

Related

Having trouble with file path in BlueJ

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));

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.

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.

adding objects to java queues from a data file

I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}

Simultaneous searching of multiple words in an external file(Java)

The program that I am trying to create is a program that takes words from a user defined file, saves those words as variables and then searches a different user defined file for those words, outputting there location.
The program works up to and including the point where the program takes the words and saves them as variables. The problem with the program is that the search method returns a null result. My main suspicions are that the code in the search method is incompatible with the code in the read method, or that the 2 methods aren't running simultaneously.
The search method is in the searching class and the read method is in the reading class.
Here is my code (Containing all 3 of my classes), please excuse all of the imports.
This is the first class:
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Combination{
public static void main(String[] args) throws FileNotFoundException{
Scanner userInput = new Scanner(System.in);
Reading ReadingObject = new Reading();
System.out.println("Please enter the file that you wish to open");
String temp = userInput.nextLine();
ReadingObject.setFileName(temp);
ReadingObject.read();
Scanner searchForWord = new Scanner(System.in);
Searching SearchingObject = new Searching();
System.out.println("Please enter the file that you would like to search for these words in");
String temp1 = searchForWord.nextLine();
SearchingObject.setFileName(temp1);
SearchingObject.search();
}
}
This is the second class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class Reading {
private String file;
public void setFileName(String fileName){
file = fileName;
}
public String getFileName(){
return file;
}
public void read(){
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read the file line by line
while((strLine = br.readLine()) != null){
// \\s+ means any number of whitespaces between tokens
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
System.out.print(word);
System.out.print(" ");
Searching SearchingObject = new Searching();
SearchingObject.setWord(word);
}
System.out.print("\n");
}
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
This is the third class:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Searching {
private String file1;
public void setFileName(String fileName){
file1 = fileName;
}
public String getFileName(){
return file1;
}
private String word1;
public void setWord(String wordName){
word1 = wordName;
}
public String getWord(){
return word1;
}
public void search() throws FileNotFoundException{
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null){
Pattern p = Pattern.compile(getWord());
Matcher m = p.matcher(strLine);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be greatly appreciated.
Regards
Your code is hard to read. Your reading class does not only read; it also searches. You should call it something that reflects its intended use. However, it forgets to tell its searching object where to search, and does not pass the reference to this object to anyone else. In this snippet
for (String word : words) {
System.out.print(word);
System.out.print(" ");
searching searchingObject = new searching();
searchingObject.setWord(word);
}
you are essentially not doing anything. The reference to searchingObject is lost forever.
Your reading class should keep an ArrayList of words to be searched for in the searching, instead of instancing searching objects.
Your searching class should take, as a constructor parameter, one of these ArrayLists -- and convert it into a single regex, which is much more efficient than reading the file once per word to search for. You can search for "a", "b" and "c" using the single regular expression "a|b|c". Works with longer words, too. Escape them first to avoid problems.
Oh, and please, please follow naming guidelines. Call your reading a TokenReader, and your searching a WordListSearcher...

Categories