0

I'm trying to read a file in eclipse and print it. The problem is that the compiler always says to me that the file or directory doesn't exist. I have to use relative paths.

The relevant part of the project routes is:

  • uva.pfc.refactoringEngine.core <--Project
    • ...
    • src
      • uva.pfc.refactoringengine.core.actions <-- Actual Package
        • ...
        • CreateEnumSetPlusClas.java <--File from I want to read the EnumSetPlus.java file
      • ...
      • EnumSetPlus.java <-- File I want read and print

This is the code:

String total="";

File actual = new File("src/EnumSetPlus.java"); 

FileReader filereader = null; 

try { 
filereader = new FileReader(actual); 
} 
catch (FileNotFoundException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
} 

BufferedReader input = new BufferedReader(filereader); 

try { 
while ((line = input.readLine()) != null) 
{ 
total += line + "\n"; 
} 
input.close(); 
} 
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace(); 
} 

System.out.println(total);

I think the problem is that I have to do something if I want the file path recognised by de eclipse project.

Could you help me??

Thaks beforehand.

recluising
  • 348
  • 1
  • 3
  • 13

4 Answers4

3

I'd use getClass().getResourceAsStream("/EnumSetPlus.txt") - this will look for the file on the root of the classpath (which is bin/, but all files from src go to bin). You then get an InputStream which you can adapt to Redaer via new InputStreamReader(stream, encoding)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

In Eclipse the current working directory is src by default.

Try this

File actual = new File("EnumSetPlus.txt"); 

Also I would look into Kevin's answer too. :-)

Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
1

Try:

String filePath = "/EnumSetPlus.java";
File actual = new File(ClassLoader.getSystemResource(filePath).getFile()); 
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0

Your example says that you want to read a file called EnumSetPlus.java but the source code is looking for a file called EnumSetPlus.txt.

KevinS
  • 7,715
  • 4
  • 38
  • 56