My method can't find files in directory - java

public class Cww {
static List<String> readFile(String filename) {
List<String> records = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while((line = reader.readLine()) != null)
{
records.add(line);
}
reader.close();
return records;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
and my main:
readFile("DirList.java");
File file = new File("DirList.java");
System.out.println(file.getCanonicalPath());
// CLASSPATH: .;..;J:\Programowanie\eclipse workspace\tij;C:\Program Files\Java\jre7\lib\ext\QTJava.zip
output: java.io.FileNotFoundException: DirList.java (Nie można odnaleźć określonego pliku)
J:\Programowanie\eclipse workspace\Rozdzial 18 cwiczenia\DirList.java
file.getCanonicalPath() shows that jvm search for my file where it really is, but my fileRead method is still giving me error,
Do I need to include every project folder in my classpath to read files from them ?
Thanks in advance

The File constructor argument is an absolute or relative filename. It will not use the classpath, the filename is - if not absolute - always relative to the current working directory.

FileReader(filename) will open a "DirList.java" in the directory from where your java code was executed (relative path). It is not related to the CLASSPATH in any way.

Related

How to read data from more than 1 text files using regular Expression in java?

Given more than one files in a directory
I have to read only the text files from a directory and print all the information inside it.
My Implementation:
File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
Matcher m=p.matcher(s1[i]);
if(m.find()&&m.equals(s1));
System.out.println(s1[i]);
File file1=new File(s1[i]);
readFromFile(file1);
}
static void readFromFile(File filename) throws IOException{
String line = null;
FileReader fileReader = new FileReader(filename); //1
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
}
While running the above program i am getting NullPointer at position 1 as indicated in the code.
Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.
But I wanted to know how using above implementation I can read all the data inside the text files.
Can anyone guide me on this how to correctly handle the above approach.
You probably have a problem while reading the file.
To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):
public static void main (String[] args) {
readFromFile(new File("nonexistant.txt"));
}
public static void readFromFile(File file) {
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
for (String line = bufferedReader.readLine();
line != null;
line = bufferedReader.readLine()) {
System.out.println(line);
}
} catch (Exception ex) {
System.err.print(ex);
}
}
Here it prints the reason:
java.io.FileNotFoundException: nonexistant.txt (No such file or directory)
Once you have fixed this issue, move to the file parsing.

Read an existing text file in Java

I'm a Java Beginner and I'm trying to make a program of reading from an existing text file. I've tried my best, but it keep on saying "File Not Found!". I've copied my "Test.txt" to both the folders - src and bin of my package.
Kindly help me into this. I'll be very thankful. Here's the code -
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}
If you are just putting Test.txt then the program is looking in the root folder of the project. Example:
Project
-src
--package
---class
-bin
-Test.txt
Test.txt needs to be in the same directory as src and bin, not inside of them
If your folder structure is like this (The Text.txt file inside src folder)
+src
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);
Or If your folder structure is like this
+src
+somepackage
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);
Pass a String (or File) with the relative path to your project folder (if you have your file inside src folder, this should be "src/Test.txt", not "Test.txt").
For read a text file you should use FileReader and BufferedReader, BufferedReader have methods for read completed lines, you can read until you found null.
An example:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}
Tons of ways to accomplish this! I noticed that you specify args[0], why?
// Java Program to illustrate reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}

Java FileNotFoundException although file is there

I set up the method to try/catch this error. My issue is that it catches the fileNotFoundException for Trivia.txt even when I explicitly created Trivia.txt in the same package. I can't figure out why the file is not being found. I did some looking around for the answer to my problem, and had no luck. Anyway, here's my code
public static void readFile(){
try{
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
System.out.println();
}
catch(IOException e){
System.out.println("error reading file");
}
}
The code here is just a method of the TextHandler class that is called statically by WindowComp class (totally unrelated class). The package is mainPackage which holds the main() and WindowComp() and textHandler() alond with Triva.Txt
The way you open the file, it's supposed to be found in the current working directory, not in the subdirectory your source is found.
Try System.out.println(file.getCanonicalPath()) in order to find out where the code is expecting the file.
Try loading your file as a Resource, like this
URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());
This will load your file from the same package of the class who loads the resource.
You can also provide an absolute path for your file, using
URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");
If the file is found somewhere away from the current package of the class, you can also provide an absolute path directly to the constructor:
File file = new File("path/to/file/Trivia.txt");
You can also use a different constructor such as the one indicated in this answer:
Java - creating new file, how do I specify the directory with a method?
For further information, there's always the documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html

Java Filenotfound exception in jar file

i wrote a program, but when my friends try to execute it it throw filenotfound exception, but the file is exist, here is my code, and in the folder have lib folder, the jar file and the "csv fajlok" and in the csv fajlok folder there is the 2 csv file
String csvFile = "csv fajlok\\pontcsoport.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] pontGroupLine = line.split(";");
String[] price_split = pontGroupLine[1].split(" ");
try{
doubleDTList.add(Double.parseDouble(price_split[0]));
}catch(NumberFormatException e){
}
}
}catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Nem található a pontcsoport fájl (/csv fajlok)");
}catch (IOException e) {
}finally {
if (br != null) {
try {
br.close();
}catch (IOException e) {
}
}
}
If the file is outside the jar file, you should put an absolute path, or the "csv fajlok" folder should be in the same folder where you execute the jar file.
If the file is inside the jar file, you cannot access to it as a file but as a Stream, with the method Class.getResourceAsStream(String path).
Better to use Java NIO2 to read the file content:
List<String> lines = Files.readAllLines(Paths.get("path-to-file"), charset);
It's allow to avoid using while loop with redundant readers.
What is the OS installed on failed notebooks?
Also try to change folder name using '_' instead of space. I think it's the main reason of the issue.

Cannot find file in netbeans + glassfish project

Here it is my folder project
I would like to read the file book-form.html which is in the directory web of my project and put it in a String.
This is how I call my function 'getFileContent':
String content = getFileContent("web/book-form.html");
And this is the function:
public String getFileContent(String filePath){
String line, content = new String();
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
content += line;
}
br.close();
fr.close();
} catch(IOException e){
System.out.println(e.getMessage());
}
return content;
}
My problem is that netbeans tell me that it cannot find my file book-form.html
Any ideas ?
File path to resource in our war/WEB-INF folder?
Also you should close stream in a final block or use try-with-resource if you use jdk 7+
I find the way to do it:
Basically the program is in the main folder of Glassfish, so it's needed to put the entire path of your file from the root of your system to allow the program to find your file.

Categories

Resources