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
Related
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
I am using AWS Textract in a Java Spring boot project. I have set up AWS CLI and have the SDK as a maven dependency.
I have written Java code, converted from C# in order to extract the Key and Value pairs and I am receiving the following error after successfully extracting some words
"AGENCYCUSTOMERID:FEIN(ifapplicable)MARITALSTATUS/CIVILUNION(ifapplicable)INSUREDLOCATIONCODEBUSPRIMARYE-MAILADDRESS:FEIN(ifapplicable)LINEOFBUSINESSCELLMARITALSTATUScivilUNION(ifapplicable)CELLCELLHOME":
AGENCYCUSTOMERID:FEIN(ifapplicable)MARITALSTATUS/CIVILUNION(ifapplicable)INSUREDLOCATIONCODEBUSPRIMARYE-MAILADDRESS:FEIN(ifapplicable)LINEOFBUSINESSCELLMARITALSTATUScivilUNION(ifapplicable)CELLCELLHOMEException in thread "main" java.lang.NullPointerException
at ai.tautona.lloyds.mailboxprocessor.service.AWSTextractService.Get_text(AWSTextractService.java:112)
at ai.tautona.lloyds.mailboxprocessor.service.AWSTextractService.getKVMapRelationship(AWSTextractService.java:74)
at ai.tautona.lloyds.mailboxprocessor.service.AWSTextractService.getKVMap(AWSTextractService.java:57)
at ai.tautona.lloyds.mailboxprocessor.service.AWSTextractService.main(AWSTextractService.java:148)
Through debugging I found the line that is causing the error to be :
text += "X ";
It appears that after finding a SELECTION ELEMENT / CHECKBOX it fails?
My code :
public class AWSTextractService {
public static void getKVMap(String localFile) throws IOException {
File file = new File(localFile);
byte[] fileContent = Files.readAllBytes(file.toPath());
AmazonTextract client = AmazonTextractClientBuilder.defaultClient();
AnalyzeDocumentRequest request = new AnalyzeDocumentRequest()
.withDocument(new Document()
.withBytes(ByteBuffer.wrap(fileContent))).withFeatureTypes(FeatureType.FORMS);
AnalyzeDocumentResult result = client.analyzeDocument(request);
//Get the text blocks
List<Block> blocks = result.getBlocks();
//get key and value maps
List<Block> key_map = new ArrayList<>();
List<Block> value_map = new ArrayList<>();
List<Block> block_map = new ArrayList<>();
for (Block block : blocks) {
block_map.add(block);
if (block.getBlockType().equals("KEY_VALUE_SET")) {
if (block.getEntityTypes().contains("KEY")) {
key_map.add(block);
} else {
value_map.add(block);
}
}
}
//Get Key Value relationship
getKVMapRelationship(key_map, value_map, block_map).forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
getKeyValueRelationship.forEach((k,v)-> System.out.println("key: "+k+" value:"+v));
}
#NotNull
public static HashMap<String, String> getKVMapRelationship(List<Block> key_map, List<Block> value_map, List<Block> block_map) throws IOException {
HashMap<String, String> kvs = new HashMap<>();
;
Block value_block;
String key, val = "";
for (Block key_block : key_map) {
value_block = Find_value_block(key_block, value_map);
key = Get_text(key_block, block_map);
val = Get_text(value_block, block_map);
System.out.printf(key, val);
kvs.put("1", "2");
}
return kvs;
}
#NotNull
public static Block Find_value_block(Block block, List<Block> value_map) {
Block value_block = new Block();
for (Relationship relationship : block.getRelationships()) {
if (relationship.getType().equals("VALUE")) {
for (String value_id : relationship.getIds()) {
for (Block value : value_map) {
if (value.getId().equals(value_id)) {
value_block = value;
}
}
}
}
}
return value_block;
}
//null
#NotNull
public static String Get_text(Block result, List<Block> block_map) throws IOException {
String text = "";
Block word = new Block();
Block word2 = null;
if (result.getRelationships().stream().count() > 0) {
for (Relationship relationship : result.getRelationships()) {
if (relationship.getType().equals("CHILD")) {
for (String child_id : relationship.getIds()) {
word = block_map.stream()
.filter((x)-> x.getId().equals(child_id)).findFirst().orElse(word2);
if (word.getBlockType().equals("WORD"))
{
text += (word.getText() ==null ? "" : word.getText()) + "";
}
if (word.getBlockType().equals("SELECTION_ELEMENT"))
{
if(word.getSelectionStatus().equals("SELECTED"))
{
text += "X ";
}
}
}
}
}
}
return text;
}
public static void main (String[]args) throws IOException {
String fileStr = "/home/daniel/Documents/atrium_sources/accordImage-1.png";
AWSTextractService.getKVMap(fileStr);
System.out.println("Done!");
}
}
Im not sure what is the issue?
I am very sure other Java Devs are going to appreciate this Code. I answered my question with the help of Rikus.
package ai.tautona.lloyds.mailboxprocessor.service;
import com.amazonaws.services.textract.AmazonTextract;
import com.amazonaws.services.textract.AmazonTextractClientBuilder;
import com.amazonaws.services.textract.model.Document;
import java.nio.file.Files;
import com.amazonaws.services.textract.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
#Service
#Transactional
public class AWSTextractService {
public static void getKVMap(String localFile) throws IOException {
File file = new File(localFile);
byte[] fileContent = Files.readAllBytes(file.toPath());
AmazonTextract client = AmazonTextractClientBuilder.defaultClient();
AnalyzeDocumentRequest request = new AnalyzeDocumentRequest()
.withDocument(new Document()
.withBytes(ByteBuffer.wrap(fileContent))).withFeatureTypes(FeatureType.FORMS);
AnalyzeDocumentResult result = client.analyzeDocument(request);
//Get the text blocks
List<Block> blocks = result.getBlocks();
//get key and value maps
List<Block> key_map = new ArrayList<>();
List<Block> value_map = new ArrayList<>();
List<Block> block_map = new ArrayList<>();
for (Block block : blocks) {
block_map.add(block);
if (block.getBlockType().equals("KEY_VALUE_SET")) {
if (block.getEntityTypes().contains("KEY")) {
key_map.add(block);
} else {
value_map.add(block);
}
}
}
//Get Key Value relationship
getKVMapRelationship(key_map, value_map, block_map).forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
}
#NotNull
public static HashMap<String, String> getKVMapRelationship(List<Block> key_map, List<Block> value_map, List<Block> block_map) throws IOException {
HashMap<String, String> kvs = new HashMap<>();
;
Block value_block;
String key, val = "";
for (Block key_block : key_map) {
value_block = Find_value_block(key_block, value_map);
key = Get_text(key_block, block_map);
val = Get_text(value_block, block_map);
kvs.put(key, val);
}
return kvs;
}
#NotNull
public static Block Find_value_block(Block block, List<Block> value_map) {
Block value_block = new Block();
for (Relationship relationship : block.getRelationships()) {
if (relationship.getType().equals("VALUE")) {
for (String value_id : relationship.getIds()) {
for (Block value : value_map) {
if (value.getId().equals(value_id)) {
value_block = value;
}
}
}
}
}
return value_block;
}
//null
#NotNull
public static String Get_text(Block result, List<Block> block_map) throws IOException {
String text = "";
Block word2= new Block();
try {
if (result != null
&& CollectionUtils.isNotEmpty(result.getRelationships())) {
for (Relationship relationship : result.getRelationships()) {
if (relationship.getType().equals("CHILD")) {
for (String id : relationship.getIds()) {
Block word= (block_map.stream().filter(x-> x.getId().equals(id)).findFirst().orElse(word2));
if (word.getBlockType().equals("WORD")) {
text += word.getText() + " ";
} else if (word.getBlockType().equals("SELECTION_ELEMENT")) {
if (word.getSelectionStatus().equals("SELECTED")) {
text += "X ";
}
}
}
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return text;
}
public static void main (String[]args) throws IOException {
String fileStr = "/home/daniel/Documents/atrium_sources/accordImage-1.png";
AWSTextractService.getKVMap(fileStr);
System.out.println("Done!");
}
}
I'm writing a java program whose operation is summarized as follows:
The subfolder with the specified name is selected in the source
folder.
All the pdfs are taken and converted into txt files in
the target folder.
The name of an item is searched inside the
txt.
If the name is found then the pdf from source to target is
copied.
All the txt from the target folder are deleted, in this
way all the pdfs containing the searched word remain.
"It all works", the problem is that the txt files are not deleted from target and I can not understand why. Thanks in advance, best regards.
Launcher.java:
import java.lang.String;
import java.util.Scanner;
import java.io.File;
public class Launcher {
// campi
int status = 1;
static String source = "C:\\Users\\MyUser\\Desktop\\source\\";
static String target = "C:\\Users\\MyUser\\Desktop\\target\\";
public static void main(String [] args) {
// strings
String src = source;
String item = "";
// init
Scanner scan = new Scanner(System.in);
System.out.print("\nFornitore: ");
src += scan.nextLine().toUpperCase() + "\\";
System.out.print("Item: ");
item = scan.nextLine();
// notifier
Launcher launcher = new Launcher();
// threads
MakerThread maker = new MakerThread(launcher, src, target);
SearcherThread searcher = new SearcherThread(launcher, src, target, item);
CleanupThread cleaner = new CleanupThread(launcher, target);
// run
maker.start();
searcher.start();
cleaner.start();
}
}
MakerThread.java:
import java.io.File;
public class MakerThread extends Thread {
// campi
String src = "";
String target = "";
Launcher launcher;
// costruttore
public MakerThread(Launcher launcher, String src, String target) {
this.src = src;
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.src);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 1){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("pdf")) {
System.out.println("PDF TROVATO: " + f.getName());
// input
String input = win_str(src + f.getName());
// output
String output = target;
output += f.getName().replaceAll(".pdf", ".txt");
output = win_str(output);
// command
String command = "cmd /C java -jar ./pdfbox-app-2.0.11.jar ExtractText ";
command += input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 2;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
SearcherThread.java:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
public class SearcherThread extends Thread {
// campi
String src = "";
String target = "";
String item = "";
Launcher launcher;
// costruttore
public SearcherThread(Launcher launcher, String src, String target, String item) {
this.target = target;
this.src = src;
this.item = item;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for(File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 2){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("SEARCHING IN: " + f.getName());
// init
String line;
BufferedReader br = new BufferedReader(new FileReader(new File(target+f.getName())));
// txt search
while((line = br.readLine()) != null) {
if(line.contains(item)) {
System.out.println(" [" + item + "]" + " trovato in " + f.getName() + "\n");
// input
String pdf = f.getName().replaceAll(".txt", ".pdf");
String input = win_str(src+pdf);
// output
String output = win_str(target);
// command
String command = "cmd /C copy " + input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
break;
}
}
}
}
// set status, awake other threads
launcher.status = 3;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
CleanupThread.java:
import java.io.File;
public class CleanupThread extends Thread {
// campi
String target = "";
Launcher launcher;
// costruttore
public CleanupThread(Launcher launcher, String target) {
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 3){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("CLEANING UP: " + f.getName());
// input
String input = win_str(target + f.getName());
// command
String command = "cmd /C del " + input;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 1;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
I am trying to search for a text file in multiple directories, then add the directory path to an array list.
How can I do this?
Here is what I have so far:
File folder = new File("path\\dir");
File folder1 = new File("path\\dir1");
ArrayList<File> flielist = new ArrayList<File>();
flielist.add(folder);
flielist.add(folder1);
for (int i = 0; i < flielist.size(); i++){
File dir = flielist.get(i);
System.out.println(dir.getName());
if(dir.listFiles() != null){
for (File file : dir.listFiles())
{
String filename = file.getName();
if(filename.equals("rashed")){
System.out.println("found" + file.getPath());
}
}
}
}
public class FileSearch {
private List<String> result;
public List<String> getResult() {
if (result == null) {
result = new ArrayList<String>();
}
return result;
}
public static void main(String[] args) {
FileSearch fileSearch = new FileSearch();
fileSearch.search(new File("C:/Users"), "rashed.txt");
int count = fileSearch.getResult().size();
if (count == 0) {
System.out.println("\nNo result found!");
} else {
System.out.println("\nFound " + count + " result!\n");
for (String matched : fileSearch.getResult()) {
System.out.println("Found : " + matched);
}
}
}
public void search(File file, String filename) {
if (file.isDirectory()) {
System.out.println("Searching directory ... " + file.getAbsoluteFile());
//do you have permission to read this directory?
if (file.canRead()) {
if (file.listFiles() != null) {
for (File temp : file.listFiles()) {
if (temp.isDirectory()) {
search(temp, filename);
} else {
if (filename.equalsIgnoreCase(temp.getName())) {
getResult().add(temp.getAbsoluteFile().toString());
}
}
}
}
} else {
System.out.println(file.getAbsoluteFile() + "Permission Denied");
}
}
}
}
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.