Droid Gamer
Droid Gamer

Reputation: 19

java trouble getting FileReader to work

root directory is named CopyFile, has directories files and src. files has the text file loremipsum.txt. src has com/example/java/Main.java

this is the code in Main.java

package com.example.java;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

public class Main {

    public static void main(String[] args) {

        String sourceFile = "files/loremipsum.txt";
        String targetFile = "files/target.txt";

        try (FileReader fReader = new FileReader(sourceFile);
             BufferedReader bReader = new BufferedReader(fReader);
             FileWriter writer = new FileWriter(targetFile)){

            while (true){
                String line =  bReader.readLine();
                if (line == null) {
                    break;
                } else{
                    writer.write(line + "\n");
                }
            }

            System.out.println("File Copied!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Below is the error:

java.io.FileNotFoundException: files/loremipsum.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at com.example.java.Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Process finished with exit code 0

Upvotes: 0

Views: 644

Answers (1)

Harmelodic
Harmelodic

Reputation: 6139

If you put this above your variables defining your file locations:

File here = new File(".");
System.out.println(here.getAbsolutePath());

You'll see that Java is looking for the files at the root directory of your project and not anywhere inside src or out.

So, your project directory tree should look like this (assuming IntelliJ):

ProjectName/  
    .idea/
    files/
        loremipsum.txt
        target.txt
    out/
        production/
            ProjectName/
                package.name/
                     Main.class
    src/
        package.name/
                Main.java
    ProjectName.iml

Upvotes: 1

Related Questions