How to Access variable from another class in same package in java - java

I want to access the class Totalnoofwords in class newrepeatedcount.
I want to print "a" of class Totalnoofwords megring with
System.out.println("( "+file1.getName() +" )-" +"Total words counted:"+total);
in class newrepeatedcount.
So I could run both the code for getting System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
Here is the snippet of 1 output which I wanted
( filenameBlog 39.txt )-Total no of words=83,total repeated words counted:4
Any suggestions Welcomed.
I am a beginner to java.
Here is my two class codes below.:)
Totalnoofwords.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.apache.commons.io.FileUtils;
public class Totalnoofwords
{
public static void main(String[] args)
{
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader (
new InputStreamReader(
new FileInputStream(file1)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "", str = "";
int a = 0;
int b = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
b++;
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
System.out.println(" Total no of words=" + a );
}
}
}
newrepeatedcount.java
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
//show the output
int total=0;
//System.out.println("Duplicate words:");
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
//System.out.println("Total words counted: "+total);
//System.out.println("Total no of repeated words : "+total+" ");
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total);
}
}}
I tried to put both the code into a single class
but neither one of the variable is working
System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
When I run neither "a" or "total" is working.(vice versa) If i change the code (variable)order.
Anyone tell how should I get both the variable output??
:)
Here is my updated code.below.
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = "", str = "";
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
int a = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st1 = new StringTokenizer(str);
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
a++;
}
int total=0;
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total+","+"total no of words:"+a);
// System.out.println("total no of words:"+a);
}
}}

package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}

The variables inside the main function cannot be accessed from other class.
So you can modify Totalnoofwords.java something like.
package Packagename;
public class Totalnoofwords
{
static int a = 1;
public void somename(){
Totalnoofwords A=new Totalnoofwords();
A.a+=5;
System.out.println("a"+A.a);
}
}
and your newrepeatedcount.java be like
package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}

It looks like you have 2 main methods in the same package, I'm not sure if you wanted it this way or not, but this won't work because your not overloading the methods. For instance currently you have public static void main(String[] args) in one class, If you change the other class to accept an extra argument public static void main(String[] args1, String[]args2).
Also in order to access your second class, as stated above you would use something like
Totalnoofwords totalNoofWords = new Totalnoofwords();
totalNoofWords.accessSomething();
But this won't work, because you don't have a constructor.

Related

How to implement a Java program to count the number of keywords in a Java file

I am developing a program to read the keywords from a Java file. My goal is to display the total number of keywords excluding the keywords from the strings and comments.
My attempt
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.io.File;
import java.util.Arrays;
public class Exercise21_03 {
public static void main(String args[]){
String filename = args[0];
// Step 1: read the file.
File file = new File(filename);
if(file.exists()){
try {
System.out.println("The number of keywords in "+ filename + " is "+ countKeywords(file));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
else {
System.out.println("File "+ filename + " does not exist");
}
}
public static int countKeywords(File file) throws Exception {
// Array of all Java keywords + true, ffalse and null
String[] keywordString = {"abstract", "assert", "boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","for","final","finally","float","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synhronized","this","throw","throws","transient","try","void","volatile","while","true","false","null"};
Set<String> keywordSet = new HashSet<>(Arrays.asList(keywordString));
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st = br.readLine()) != null){
String[] words = st.split(" ");
for(String word : words)
if(keywordSet.contains(word))
count++;
}
return count;
}
}
Welcome.java
public class Welcome {
public static void main(String[] args) {
// Display message Welcome to Java! on the console
// abstract
System.out.println("Welcome to Java!");
}
}
Expected:
java Exercise21_03 Welcome.java
The number of keywords in Welcome.java is 5
Actual
java Exercise21_03 Welcome.java
The number of keywords in Welcome.java is 6
How can I process this?
I believe this will do the trick
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.io.File;
import java.util.Arrays;
public class Exercise21_03 {
public static void main(String args[]){
String filename = args[0];
// Step 1: read the file.
File file = new File(filename);
if(file.exists()){
try {
System.out.println("The number of keywords in "+ filename + " is "+ countKeywords(file));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
else {
System.out.println("File "+ filename + " does not exist");
}
}
public static int countKeywords(File file) throws Exception {
// Array of all Java keywords + true, ffalse and null
String[] keywordString = {"abstract", "assert", "boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","for","final","finally","float","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synhronized","this","throw","throws","transient","try","void","volatile","while","true","false","null"};
Set<String> keywordSet = new HashSet<>(Arrays.asList(keywordString));
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st = br.readLine()) != null){
String[] words = st.split(" ");
if(Arrays.asList(words).contains("//"))
continue;
for(String word : words)
if(keywordSet.contains(word))
count++;
}
return count;
}
}

How to serialise and de-serialise an object in Java?

I need to modify class PrimeFactors so that it extends HashMap<Integer,ArrayList> and implements Serializable.
Let x be a number and y be an ArrayList containing the prime factors of x: add all <x,y> pairs to PrimeFactors and serialize the object into a new file.
Then write a method that de-serializes the PrimeFactors object from the file and displays the <x,y> pairs.
Right now, I am completely stuck and unsure how to continue. Any help would be greatly appreciated as I am very unfamiliar with this situation.
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.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.ObjectOutputStream;
public class PrimeFactors2 extends HashMap<Integer,ArrayList<Integer>> implements Serializable {
public static void findFactor(int n) {
System.out.print("Factors for the number " + n + " is: ");
for (int i = n; i >= 1; i--) {
if (n % i == 0)
System.out.print(i + " ");
}
}
public static boolean checkForPrime(int number) {
boolean isItPrime = true;
if (number <= 1) {
isItPrime = false;
return isItPrime;
} else {
for (int i = 2; i <= number / 2; i++) {
if ((number % i) == 0) {
isItPrime = false;
break;
}
}
return isItPrime;
}
}
public static void main(String[] args) {
String path = "/Users/benharrington/Desktop/primeOrNot.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<Integer> list = new ArrayList<Integer>();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
int i = Integer.parseInt(str);
boolean isItPrime = checkForPrime(i);
if (isItPrime)
System.out.println(i + " is Prime");
else
System.out.println(i + " is not Prime");
if (isItPrime == false) {
list.add(i);
}
}
for (int k : list) {
System.out.println(" ");
findFactor(k);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What you did in your code is simply reading a file and parsing it.
If you want to serialize and se-derialize an object, it can be done with the following code:
PrimeFactors2 primeFactors2 = // you object creation code here;
// i.e:
// PrimeFactors2 primeFactors2 = new PrimeFactors2();
// primeFactors2.setX1(2);
// primeFactors2.setX2(3);
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/obj.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(primeFactors2);
out.close();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, in some context (same or another) in the same moment (or whenvever after you created the .ser object), you may de-serialize it with the following code:
try {
FileInputStream fileIn = new FileInputStream("/tmp/obj.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
PrimeFactors2 primeFactors2 = (PrimeFactors2) in.readObject();
// YAY!!! primeFactors2 is an object with the same values you created before
// i.e: primeFactors.getX1() is 2
// primeFactors.getX2() is 3
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}

Split with new line and store in datastructure

I have text file data like :
2,2,1
data1,123,89,1
data2,124,90,2
data3,125,91,3
data4,126,92,4
data5,127,93,5
data6,128,94,6
data7,129,95,7
data8,130,96,8
data9,131,97,9
data10,132,98,10
The first line 2,2,1 indicate 2 lines from 1st set of lines and store it in nodeFile, 2 lines from 2nd set of lines store it in linkFile and 1 line from 3rd set of lines store it in moduleFile. However for example purpose I have shows small number of lines but its a larger file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
static int a[];
public static void main(String[] args) {
File file11 = new File("/home/madhu/Desktop/node.txt");
Scanner scAll = null;
try {
scAll = new Scanner(file11);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] numberOfLines = (scAll.nextLine()).split(",");
int flag = 0;
int counter = 1;
while (scAll.hasNext()) {
if (flag == 0 && "\\n\\n".equals(scAll.nextLine()) && counter <= Integer.parseInt(numberOfLines[0].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[0].trim()); i++) {
System.out.println(scAll.nextLine());
nodeFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[0].trim())) {
flag = 1;
counter = 1;
}
} else if (flag == 1 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[1].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[1].trim()); i++) {
System.out.println(scAll.nextLine());
linkFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[1].trim())) {
flag = 2;
counter = 1;
}
} else if (flag == 2 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[2].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[2].trim()); i++) {
System.out.println(scAll.nextLine());
moduleFile.add(scAll.nextLine());
counter++;
}
} else {
continue;
}
}
scAll.close();
}
}
I have written the above code, but this code gets terminated during execution. How to get the desired result? Please help.
Hopefully I am not misunderstanding, but this is what I'd do.
I didn't check to see if this is fully working example, but it should work more or less.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class ReadFile {
// basically just do what you did
static List<String> nodeFile;
static List<String> linkFile;
static List<String> moduleFile;
public static void main(String[] args) throws FileNotFoundException {
final File file = new File("/home/madhu/Desktop/node.txt");
final Scanner scanner = new Scanner(file);
// make it a little better for indexing
final List<Integer> selections = Arrays
.stream(scanner.nextLine().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
// this is the meat of the code
// basically each split up block of lines is a block
final List<List<String>> blocks = new ArrayList<>();
while (scanner.hasNextLine()) {
List<String> lines = new ArrayList<>();
String line;
while (!(line = scanner.nextLine()).equals("\n")) {
lines.add(line);
}
if (!lines.isEmpty()) {
blocks.add(lines);
}
}
// allocate your files now
nodeFile = blocks.get(0).subList(0, selections.get(0));
linkFile = blocks.get(1).subList(0, selections.get(1));
moduleFile = blocks.get(2).subList(0, selections.get(2));
scanner.close();
}
}
try this code , i use BufferedReader because its more cleaner :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
public static void main(String[] args) {
File file = new File("/home/madhu/Desktop/node.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String data[] = reader.readLine().split(",");
String s;
int nbline=0, i=0,block =0;
while ((s = reader.readLine())!=null && block < data.length) {
if(s.equals("")){
block++;
nbline = Integer.parseInt(data[block-1]);
i = 0;
}
for(;i<nbline;i++){
s = reader.readLine();
if(s == null) break;
else if(s.equals("")){
block++;
break;
}
switch(block){
case 1 :
nodeFile.add(s);
break;
case 2:
linkFile.add(s);
break;
default: moduleFile.add(s);
}
}
}
} catch (IOException | NumberFormatException ex) {
System.err.println(ex.getStackTrace());
}
finally{
closeReader(reader);
}
System.out.println("nodeFile : "+nodeFile);
System.out.println("linkFile : "+linkFile);
System.out.println("moduleFile : "+moduleFile);
}
public static void closeReader(BufferedReader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
output :
nodeFile : [data1,123,89,1, data2,124,90,2]
linkFile : [data5,127,93,5, data6,128,94,6]
moduleFile : [data8,130,96,8]

The infinite monkey theorem in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:
package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* #author robi1
*/
public class RandomString {
public static void main(String[] args){
List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "final.txt");
String letters = "abcdefghijklmnopqrstuvwxyz ";
Object[] wrds = readFile("basicWordsInEnglish.txt");
int x = wrds.length;
String[] words = new String[x];
for(int i =0;i<x;i++){
words[i] = wrds[i].toString();
}
char[] let = letters.toCharArray();
String n ="";
Random r = new Random();
char t;
}
public static Object[] readFile(String name){
ArrayList<String> al = new ArrayList<String>();
FileInputStream fstream;
try {
fstream = new FileInputStream(name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine=br.readLine())!=null){
if(strLine.length()>4)
al.add(strLine);
}
fstream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object[] array = al.toArray();
return array;
}
public static List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public RandomString(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.
public void main(String... args) {
List<String> dictionary = readDictionaryFrom("path to dictionary");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "path to destination file");
}
public List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10_000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
Use the debugging feature of your favorite IDE (might be Eclipse), set an exception breakpoint on ArrayIndexOutOfBoundsException, run your program in debug mode.
When it hits the exception, Eclipse will halt your program. Look at your variable values, especially which array you are accessing and what value the index has, and why it got a value outside of the array size.
By the way, your code line if(n.length()>4){ cannot produce an ArrayIndexOutOfBoundsException, as there's no array indexing in that line.

FileNotFound exception while files already exist

this code couldn't find the files that the buffered reader is supposed to read from it and i have the files in the src folder in eclipse project and it still doesn't read from file so does anybody have any idea about what the problem is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.*;
import java.util.ArrayList;
public class Encrypt {
public static ArrayList<String> data = new ArrayList<String>();
public static BigInteger [] keys = new BigInteger[3];
public static BigInteger n;
public static double e;
public static BigInteger d;
public static String line;
public static String result;
public static String [] temp;
public static BigInteger tempVar;
public static BigInteger tempResult;
public static int tempVar2;
public static void encryption(ArrayList<String> data) throws IOException{
for (int i = 0; i<data.size(); i++){
if(data.get(i)!= null){
temp = new String[data.get(i).split(" ").length];
temp = data.get(i).split(" ");
for(int j = 0; j<temp.length;j++){
for (int k = 0; k< temp[j].length(); k++){
tempVar2 = (int)temp[j].charAt(k);
tempVar=BigInteger.valueOf((long)Math.pow(tempVar2,e));
tempResult = (tempVar.remainder(n));
result =""+ tempResult;
LogEncrypt(result);
}
}
}
}
}
public static void read() throws IOException{
try {
BufferedReader br = new BufferedReader(new FileReader("plainText.txt"));
System.out.println(br.ready());
while ((line = br.readLine()) != null) {
data.add(br.readLine());
}
System.out.println("done with text");
} catch (FileNotFoundException e) {
System.out.println("please add the text file");
e.printStackTrace();
}
try {
BufferedReader ba = new BufferedReader(new FileReader("Key.txt"));
System.out.println(ba.ready());
int i =0;
while ((line = ba.readLine()) != null) {
keys[i] = new BigInteger(ba.readLine());
i++;
}
n = keys[0];
e = keys[1].doubleValue();
d = keys[2];
System.out.println("done with key");
} catch (FileNotFoundException e) {
System.out.println("please add the key file");
e.printStackTrace();
}
}
public static void LogEncrypt(String result) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
try {
out.write(result);
out.newLine();
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
}
}
public static void main(String[]args) throws IOException{
read();
encryption(data);
}
}
Put the file outside of the src, or at least add "src/" to the file location

Categories

Resources