I am trying to get the GETTER of "FileHandler.java" to return the value(final_match) to "main.java" and out put. Problem is that final_match outputs as 0. In "FileHandler.java" Outside of my getter final_match has the correct value, but when called/returned from the GETTER value is plain 0
main.java
package textreader;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public String data = "";
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
final File directory = new File("E:\\test\\filename.txt");
// final File directory2 = new File("E:\\test\\filename2.txt");
ArrayList<File> f = new ArrayList<>();
f.add(directory);
// f.add(directory2);
final String words;
System.out.println("The word you would like to search for. ");
System.out.println("----------------------------------------");
words = user_input.next();
main aMain = new main(f, words);
}
main(ArrayList<File> f, String words) { //constructor
ArrayList<FileHandler> threadArray = new ArrayList<>();//arraylist of type filehandler
for (File file : f) {
FileHandler fh = new FileHandler(this, words, file);// instance of filehandler = fh
threadArray.add(fh);
fh.start();
for (FileHandler x : threadArray) {
if (x.isFinished()) {
x.setFinished(true);
synchronized (x) {
x.notify();// notify next thread to continue
}
}
int answer = x.getfinal_match(); // CALLING THE GETTER FOR VALUE
System.out.println("----------------------------------------");
System.out.println("this word has appeared: " + answer + " times.");
System.out.println("----------------------------------------");
}
}
}
}
FileHander.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileHandler extends Thread {
BufferedReader br = null;
FileReader fr = null;
String words;
File file;
int counter;
int match;
int final_match;
boolean done = true;
boolean finished;
private final main main;
public FileHandler(main instance, String words, File file) { //constructor
this.words = words;
this.file = file;
this.main = instance;
}
#Override
public synchronized void run() {
try {
fr = new FileReader(this.file);//file path
br = new BufferedReader(fr);// reads the words in the file
String theLine;
while ((theLine = br.readLine()) != null) {
String List[] = theLine.split(" ");
for (String List1 : List) {
if (List1.equals(List[counter])) {// of words are the same as "word" increment match
match++; //Amount of occurrences
}
counter++;//loop through each word
}
synchronized (this) {
//System.out.println("test2 " + match);
this.finished = true;
}
}
} catch (IOException e) {
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
}
}
final_match = match;
System.out.println("testing " + final_match); // THIS TEST WORKS AS VALUE WAS OUTPUTTED AS 5
}
public void setfinal_match(int test) {
final_match = test;
}
public Integer getfinal_match() {
System.out.println("testing 123456 " + final_match); // THIS VALUE DOES NOT WORK AS IT OUTPUTS A BIG FAT 0
return final_match;
}
public boolean isFinished() {
return this.finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
}
//OUTPUT
//run:
//the word you would like to search for.
//----------------------------------------
//dog
//testing GETTER 123456 0
//----------------------------------------
//this word has appeared: 0 times.
//----------------------------------------
//testing 5
//BUILD SUCCESSFUL (total time: 2 seconds)
//EXPECTED OUTPUT
//run:
//The word you would like to search for.
//----------------------------------------
//dog
//testing GETTER 123456 5
//----------------------------------------
//this word has appeared: 5 times. (THIS IS THE MAIN VALUE THAT HAS TO CHANGE)
//----------------------------------------
//testing 5
//BUILD SUCCESSFUL (total time: 2 seconds)
Your final_match is 0 at the time of the output, since the thread starts and is not finished yet, when you output the value of final_match.
Related
I have just gotten into java, and i was working on an elementary project.
I tried to create a program which would locate the desired string within a txt which stored some activities, and the id associated with them (e.g:
1 Sleep
2 Exercise
3 Socializing
4 Studying
5 Transportation
6 Eating)
The code is as follows
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class ReadNSearchFile {
private static Scanner x;
public static void main(String[] args) {
String filepath = "C:\\Users\\John\\Desktop\\Java crap\\Activities.txt";
String searchTerm = "Sleep";
readRecord(searchTerm, filepath);
}
public static void readRecord(String searchTerm, String filepath) { //it will search for the ID
boolean found = false;
String ID = ""; String activity = "";
try {
x = new Scanner(new File(filepath));
x.useDelimiter("[\n\s]"); //used to separate fields in a file eg words
while(x.hasNext() && !found) {
ID = x.next();
activity = x.next();
if(activity.equals(searchTerm)) {
found = true;
}
}
if(found) {
JOptionPane.showMessageDialog(null, "ID:" + ID + "Activity: " + activity);
}else if(!found) {
JOptionPane.showMessageDialog(null, "Record not found");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "error");
}
}
}
The desired activity is contained within the text, however is not located through the code.
Why is this?
I've tried to create a program that will read multiple text files in a certain directory and then produce a frequency of the words that appear in all the text files.
Example
text file 1: hello my name is john hello my
text file 2: the weather is nice the weather is
The output would show
hello 2
my 2
name 1
is 3
john 1
the 2
weather 2
nice 1
The issue i'm having is that my program just terminates as soon as it's ran, no output is shown at all.
Here's my class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable {
public String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
File file = new File("C:\\Users\\User\\Desktop\\files\\1.txt");
if (file.isDirectory()) {
Scanner in = null;
for (File files : file.listFiles()) {
int count = 0;
try {
HashMap<String, Integer> map = new HashMap<String, Integer>();
in = new Scanner(file);
while (in.hasNext()) {
String word = in.next();
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
count++;
}
System.out.println(file + " : " + count);
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
} catch (FileNotFoundException e) {
System.out.println(file + " was not found.");
}
}
}
//in.close();
}
}
Here's my class to run them
public class Mainstackquestion {
public static void main(String args[]) {
if (args.length > 0) {
for (String filename : args) {
CheckFile(filename);
}
}
else {
CheckFile("C:\\Users\\User\\Desktop\\files\\1.txt");
}
}
private static void CheckFile(String file) {
Runnable tester = new WordCountstackquestion(file);
Thread t = new Thread(tester);
t.start();
}
}
UPDATED answer. I was wrong on the original cause of the problem. The problem was more an algorithm problem than a thread-related problem.
Code for Mainstackquestion class:
public class Mainstackquestion {
public static void main(String args[])
{
List<Thread> allThreads = new ArrayList<>();
if(args.length > 0) {
for (String filename : args) {
Thread t = CheckFile(filename);
allThreads.add(t); // We save this thread for later retrieval
t.start(); // We start the thread
}
}
else {
Thread t = CheckFile("C:\\Users\\User\\Desktop\\files");
allThreads.add(t);
t.start();
}
try {
for (Thread t : allThreads) {
t.join(); // We wait for the completion of ALL threads
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Thread CheckFile(String file) {
Runnable tester = new WordCountstackquestion(file);
return new Thread(tester);
}
}
Code for WordCountstackquestion:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable {
public String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
File dir = new File(filename);
if (dir.exists() && dir.isDirectory()) {
Scanner in = null;
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (File file : dir.listFiles()) {
if (file.exists() && !file.isDirectory()) {
int count = 0;
try {
in = new Scanner(file);
while (in.hasNextLine()) {
String line = in.nextLine();
String[] words = line.split(" ");
for (String w : words) {
if (map.containsKey(w)) {
map.put(w, map.get(w) + 1);
} else {
map.put(w, 1);
}
}
count++;
}
//System.out.println(file + " : " + count);
} catch (FileNotFoundException e) {
System.out.println(file + " was not found.");
} finally {
if (in != null) {
in.close();
}
}
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
}
}
}
Tested with the same 2 files that you gave as example.
Obtained result:
the 2
name 1
weather 2
is 3
john 1
hello 2
my 2
nice 1
I have created a simple program that takes a title and a note which you enter then you have a choice to export the notes to txt file using BufferedWriter however because each note is a object which is stored in a ArrayList when storing them I iterate through a for enhanced loop it keeps duplicating each note as I iterate through all the object.
Note Class
import java.util.*;
public class Notes
{
private String notes;
private String titleOfNotes;
Scanner input = new Scanner(System.in);
public Notes()
{
titleOfNote(input);
takeNotes(input);
}
public void takeNotes(Scanner x)
{
System.out.println("Please Enter Your Note");
notes = x.nextLine();
}
public void titleOfNote(Scanner y)
{
System.out.println("Please Enter Title");
titleOfNotes = y.nextLine();
}
public String toString()
{
return "Title: " + titleOfNotes + "\t" + notes;
}
}
App Class //Does mostof the Work
import java.util.*;
import java.io.*;
public class App
{
private int exit = 0;
private int createANote;
private int displayTheNotes;
private int inputFromUser;
public boolean haveFileBeenWritten = true;
File file = new File("Notes.txt");
Scanner input = new Scanner(System.in);
ArrayList<Notes> arrayOfNotes = new ArrayList<Notes>();
public void makeNoteObject()
{
arrayOfNotes.add(new Notes());
}
public void displayAllTheNote(ArrayList<Notes> n)
{
for(Notes singleObjectOfNote : n)
{
System.out.println(singleObjectOfNote);
}
}
public void programUI(){
while(exit != 1)
{
System.out.println("1. Create A Note");
System.out.println("2. Display The Notes");
System.out.println("3. Exit");
System.out.println("4. Export to text file");
System.out.println("Enter Your Operation");
inputFromUser = input.nextInt();
if(inputFromUser == 1)
{
makeNoteObject();
}
else if(inputFromUser == 2)
{
displayAllTheNote(arrayOfNotes);
}
else if(inputFromUser == 3)
{
System.out.println("Exited");
exit = 1;
}
else if(inputFromUser == 4)
{
makeATxtFileFromNotes(arrayOfNotes);
System.out.println("Textfile created filename: " + file.toString());
}
else
{
System.out.println("You Select A Invalid Command");
}
}
}
public void makeATxtFileFromNotes(ArrayList<Notes> x)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
{
//Problem here!
for(Notes singleObjectOfNotes : x)
{
bw.write(singleObjectOfNotes.toString());
bw.newLine();
}
}catch(IOException e)
{
System.out.println("Cant Write File: " + file.toString());
haveFileBeenWritten = false;
}
}
public App()
{
programUI();
}
public static void main(String[]args)
{
App objectOfApp = new App();
}
}
I am new to Java so my code my not be the best!
If your problem is that you only need to see current list's Notes excluding the previous', it's because of this line:
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
By default, haveFileBeenWritten is true so based on the FileWriter API it will APPEND on the existing file Notes.txt so if you don't want that, change it to false.
Parameters:
file - a File object to write to
append - if true, then bytes will be
written to the end of the file rather than the beginning
EDIT: To access List<> elements, use get().
Example:
int size = myList.size();
for (int i = 0 ; i < size ; i++) {
//...
Notes note = myList.get(i);
//...
}
I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)
I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)