I'm trying to read a file that exists in the following location of my Eclipse java project:
Tester -> src -> threads -> ReadFile.java
This is the code used:
public class Tester {
public static void main(String[] args) {
ReadFile[] readers;
readers = new ReadFile[3];
for (int intLoopCounter = 0; intLoopCounter < 3; intLoopCounter++) {
readers[intLoopCounter] =
new ReadFile("ReadFile.java", intLoopCounter);
System.out.println("Doing thread number: " + (intLoopCounter + 1));
}
}
Can you tell me what to add to:
new ReadFile("ReadFile.java"
so the file can be read?
There is a buffered reader in the ReadFile.java class file. I'm experimenting with this just to see if I can read the ReafFile.java file and show the results to the console.
Here is the code that is throwing the error from ReadFile.java:
public ReadFile(String filename, int i) {
id = i;
try {
input = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Problem occured: " + e.getMessage());
} // catch
} // Constructor
Assuming that Tester is your project root directory, your path to the file should be "src/threads/ReadFile.java". If the file trully exists it will be found.
You need to modify the path in the call to ReadFile to include a full path, a path anchored by your user directory, or a path relative to the directory in which Eclipse runs your test program.
For example, if your project is located in /Users/myuser/projects/Tester/src/threads, you can use this line:
new ReadFile("/Users/myuser/projects/Tester/src/threads/ReadFile.java", intLoopCounter)
Related
I'm trying to read a text file (dictionary.txt) which is located in src/main/resources, but I keep getting a file not found exception.
public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (Scanner sc = new Scanner(new File("/src/main/resources/dictionary/dictionary.txt"))){ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that d
}
System.out.println("Score is "+ ReviewScore);
}
}
public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (var resource = Review.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner sc = new Scanner(resource);{ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that is not found due to either typo or non-existence deduct 5pts
}
System.out.println("Score is "+ ReviewScore);
}
//frequentlyUsedWords (ReviewScore,Review);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new File. The name says it: That only works for FILES. Entries in jar files aren't themselves files.
If you write new File, or mention FileInputStream, you've lost. That cannot be made to work with this stuff.
Fortunately, you can just ask the JVM to give you a resource from the same place it loads class files, whereever those class files might be. In a jar, in a directory, live-loaded over a network - doesn't matter. You can get these resources in URL form and an InputStream form - any code that can work with those, can be made to work with 'resources that are in the same place my class files are, such as in the jar'.
Scanner is one of those things: It has a constructor that takes an inputstream. So, let's do that!
try (var resource = MyClassName.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner s = new Scanner(resource);
.. rest of code here
}
A few notes:
/dictionary/dictionary.txt means: Relative to the 'root of the jar'. If you want relative to your class file's package, don't start with a leading slash.
It's a resource, so it must be closed, hence, this code uses try-with-resources.
I am writing simple program that is looking for file and if it exists, writes his path to txt file. If not, program is freezed for 1 minute. My problem is that file path is not being printed into txt file when searched file exists. I think it is something wrong with try block. I do not know where the problem is. How can i solve it?
public class FileScanner {
public void scanFolder() throws IOException, InterruptedException {
Scanner input = new Scanner(System.in);
//tworzenie pliku logu
File log = new File("C:/Users/mateu/OneDrive/Pulpit/log.txt");
if (!log.exists()) {
log.createNewFile();
}
//obiekt zapisujacy nazwy i sciezki plikow do logu
PrintWriter printIntoLog = new PrintWriter(log);
while (true) {
//podanie sciezki szukanego pliku
System.out.println("Input file's directory you are looking for: ");
String path = input.nextLine();
//utworzenie obiektu do danego pliku
File searchedFile = new File(path);
//sprawdzenie czy plik istnieje- jesli tak to zapisuje do logu jego sciezke i usuwa go
try{
if (searchedFile.exists()) {
printIntoLog.println(searchedFile.getPath());
//searchedFile.delete();
}else{
throw new MyFileNotFoundException("Searching stopped for 1 minute.");
}
}catch(MyFileNotFoundException ex){
System.out.println(ex);
TimeUnit.MINUTES.sleep(1);
}
}
}
}
You should close the PrintWriter reference before finishing execution. It's an enforced practice to close a file after read/write on it.
If you are using Java +7 you can use the fancy way withtry-with-resources syntax
```java
try (PrintWriter printIntoLog = new PrintWriter(log)) {
while (true) {
....
}
}
```
With older versions you can use try-finally syntax
try {
while(true) {
...
}
} finally {
printIntoLog.close();
}
See
Java – Try with Resources
This question already has an answer here:
File not found java
(1 answer)
Closed 2 years ago.
I have a java project in eclipse and have a method that reads information from a file. When I do a JUnit test on the method, it is unable to find the file even though it is in my working tree and I used the correct class path declaration.
Method to read file:
public static ArrayList<Issue> readIssuesFromFile(String filename) {
ArrayList<Issue> issues = new ArrayList<Issue>();
try {
Scanner sc = new Scanner(new FileInputStream(filename));
String text = "";
while(sc.hasNextLine()) {
text+= sc.nextLine();
text+= "\n";
}
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
JUnit Test:
public void testReadIssueFromFile() {
String test = "test-files/valid_file.txt";
try {
ArrayList<Issue> issues = IssueReader.readIssuesFromFile(testFile);
assertEquals(issues.get(0).getIssueId(), 0);
} catch (Exception e) {
fail(e.getMessage());
}
}
Working Tree:
->Project
->src
->.java file containing method
->test
->JUnit test file
->test-files
->txt file
According to your working tree i think your path should be:
../test-files/valid_file.txt
The path you used (test-files/valid_file.txt) means search in the folder of your JUnit file a folder named test-files and search inside this folder a file named valid_file.txt.
According to your working tree it's not the case. So you need .. to move to the above level where you can find the folder test-files.
If it still doesn't work, maybe try to debug you program by printing the paths that you have used like this:
try {
/* Here you can replace the period with another path like "test-files/valid_file.txt"
* to see the absolute path of it
*/
System.out.print(new java.io.File( "." ).getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
I am using Eclipse and the Java Library: java.io.FileInputStream;
My script cannot find a file that I want to assign to a variable using the constructor FileInputStream even though the file is in the Working directory.
Here is my code:
package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
public static void main(String [] args){
//verify what the working directory is
String curDir = System.getProperty("user.dir");
System.out.println("Working Directory is: "+curDir);
//verify the file is recognized within within the code
File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
} else {
System.out.println("File does not exist");
}
//Assign the file to src
File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
System.out.println("SRC is now: "+src);
//Get Absolute Path of the File
System.out.println(src.getAbsolutePath());
FileInputStream fis = new FileInputStream(src);
}*
My output is (when i comment out the last line) is
"Working Directory is: C:\Users\wes\workspace\QTI_crud
Yes, File does exist
SRC is now: C:\Users\wes\workspace\QTI_crud\values.xlsx
C:\Users\wes\workspace\QTI_crud\values.xlsx"
When I don't comment out the last line, I get the error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"
Where have I gone wrong in my code? I'm pretty new to Java
Much thanks!
Major problem with the code is that you after you know that file do not exist on specified directory, you tried to read the file. Hence, it is giving you the error.
Refactor it to this
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
try {
FileInputStream fis = new FileInputStream(f);
//perform operation on the file
System.out.println(f.getAbsolutePath());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
Here as you can see, if file exists then you try to read the file. If it is not available you don't do anything.
I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}