FileNotFound exception while files already exist - java

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

Related

Unable to copy txt file over to arraylist and into file

I am attempting to add this large txt file into an array list then sort the data. Then put 15000 lines in various temp files. I am unable to put the data into each file. Here is my code:
package bigfilesorter2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class bigfilesorter2 {
public static final int NUM_LINES = 15000;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("Aesop_Shakespeare_Shelley_Twain.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<String> arraylist = readingfile(br);
//System.out.println(arraylist);
makingfiles(br, arraylist);
}
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
start = end + 1;
end += 15000;
}
}
public static ArrayList<String> readingfile(BufferedReader br) throws FileNotFoundException, IOException {
//Read in file
Scanner s = new Scanner(new File("Aesop_Shakespeare_Shelley_Twain.txt"));
int count = 0;
ArrayList<String> arraylist = new ArrayList<String>();
while (s.hasNext()) {
count++;
arraylist.add(s.nextLine());
}
//} catch (IOException e) {e.printStackTrace();}
Collections.sort(arraylist);
//System.out.println(arraylist);
return arraylist;
}
}
Any help would be appreciated. the commas were just the file being sorted..................
"it looks like your post is mostly code"
You need to create a list of sublists where each sublist holds 15000 lines. Given below is the complete code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class BigFileSorter {
public static final int NUM_LINES = 15000;
public static final int NUM_FILES = 20;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<ArrayList<String>> list = readingfile(br);
makingfiles(br, list);
}
public static void makingfiles(BufferedReader br, ArrayList<ArrayList<String>> list) throws IOException {
if (list != null) {
for (int i = 0; i < NUM_FILES; i++) {
File file = new File("Filee" + i + ".txt");
FileWriter fw = new FileWriter(file);
ArrayList<String> subList = list.get(i);
for (String str : subList) {
fw.write(str + System.lineSeparator());
}
fw.close();
}
}
}
public static ArrayList<ArrayList<String>> readingfile(BufferedReader br)
throws FileNotFoundException, IOException {
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
ArrayList<String> subList;
String line;
try {
for (int i = 0; i < NUM_FILES; i++) {
subList = new ArrayList<String>();
for (int j = 0; j < NUM_LINES; j++) {
line = br.readLine();
if (line == null) {
break;
}
subList.add(line);
}
Collections.sort(subList);
list.add(subList);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
return list;
}
}
Feel free to comment in case of any doubt.
Maybe something like this as an inner for loop in your makefiles method.
// outside of the for loops
int start = 0;
int end = 15000;
// inner for loop
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
// end of outer for loop
start = end + 1;
end += 15000;
So complete method:
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
bw.flush();
bw.close();
fw.close()
start = end + 1;
end += 15000;
}
}
Should work for what you asked in the comment, but you still have to change your read method so that it reads all the lines in one arraylist

FileWriter method doesn't print anything unless append is true

Newbie here. My goal is to read a txt file, eliminate characters ("-" and " "), and replace the existing text with the new cleaned up text.
example: 855-555-1234 >> 8555551234.
I'm stuck on my append boolean. I'm using the guides here and here.
When my append is true then I get the text that I want at the end of the file, but when it is false, the file is completely blank.
My main method looks like:
public class Main {
public static void main(String[] args) throws IOException{
String file_name = "C:/TollFreeToPort.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
WriteFile data = new WriteFile(file_name, true);
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
data.writeToFile(aryLines[i]);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
My ReadFile Class:
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine()
.replace("-", "")
.replace(" ", "");
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
My WriteFile Class:
package textfiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile (String textLine) throws IOException{
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}

How do I print my CSV file to an ArrayList?

Here is my code
package sequentialFilePractice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReadFile{
static String line = "";
ReadFile() throws FileNotFoundException{
readTheFile();
CSVtoArrayList();
}
public String readTheFile() throws FileNotFoundException{
String csvFile = "H:\\S6\\AH Computing\\Java Practice\\test.csv";
BufferedReader br = null;
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return line;
}
public static ArrayList<String> CSVtoArrayList() {
ArrayList<String> splitCSV = new ArrayList<>();
if (line != null) {
String[] splitData = line.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
splitCSV.add(splitData[i].trim());
}
}
}
for(int j = 0;j < splitCSV.size();j++){
System.out.println(splitCSV.get(j));
}
return splitCSV;
}
public static void main(String[]args) throws IOException{
ReadFile f = new ReadFile();
}
}
The code compiles and the file exists. I can print line and it prints the contents of the file however when I print the arrayList, nothing is output so it has not been copied. This is my first use of sequential files in java.
Do you HAVE to read the file manually? If not, you should check out http://opencsv.sourceforge.net/, it allows you to read a CSV directly into a List<String[]> instead of having to deal with the admin of looping, splitting the line and creating a list.
In essence reducing your code to:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();

How to Access variable from another class in same package in 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.

ArrayList not persisting between methods

I'm trying to load a csv file into an arrayList to later break it up and store it. Between my methods the arrayList is being reset to null. I'm confused as to the cause and would be grateful for any advice
package TestInput;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class Bean {
private String fileContent;
private String fileContent2;
private ArrayList<String> fileContentArray;
private int counter = 0;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public ArrayList<String> getFileContentArray() {
return fileContentArray;
}
public void setFileContentArray(ArrayList<String> fileContentArray) {
this.fileContentArray = fileContentArray;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
public String getFileContent2() {
return fileContent2;
}
public void setFileContent2(String fileContent2) {
this.fileContent2 = fileContent2;
}
public void upload() {
File file = new File("/Users/t_sedgman/Desktop/FinalProject/test_output_data.rtf");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
ArrayList<String> tempArray = new ArrayList<>();
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
tempArray.add(dis.readLine());
}
setFileContentArray(tempArray);
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
fileContent = fileContentArray.get((fileContentArray.size() - 2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void next() {
ArrayList<String> tempArray = getFileContentArray();
int size = fileContentArray.size();
if (counter <= size) {
counter++;
fileContent2 = tempArray.get(counter);
} else {
counter = 0;
}
}
}
Many Thanks
Tom
You can try By marking your bean with #ViewScoped/#SessionScoped

Categories

Resources