popster
popster

Reputation: 31

Exception java FileUtils.readFileToByteArray when trying to readFileToByteArray

My text file, mombirthday.txt, is in the same eclipse directory as my src file.

But an exception is being thrown (file does not exist).

I've tried using a qualified path to the file with another exception being thrown.

I've found countless examples but I am uncertain where the file should be located and how I should properly reference the path to the file

My project is called ReadFile, the source code and text file are both in the src directory

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class ReadFile {
  public static void main(String[] args){
    try{
    //File 'mombirthday.txt' does not exist
   //byte[] bytesInput = FileUtils.readFileToByteArray(new File("mombirthday.txt"));

   //File 'mombirthday.txt' does not exist
 byte[] bytesInput = FileUtils.readFileToByteArray(new File("/ReadFile/src/mombirthday.txt"));**

  }catch(IOException e){
   System.out.println(e.getMessage());
  }
 }
}

Upvotes: 0

Views: 9636

Answers (3)

chandrasekar
chandrasekar

Reputation: 354

public static void readFile(){
    try {
        // byte[] bytesInput = FileUtils.readFileToByteArray(new File("C:/Users/mavensi/Desktop/catalina_14.log"));
        byte[] bytesInput = IoUtils.readBytes(new File("C:/Users/mavensi/Desktop/catalina_14.log"));
        System.err.println(bytesInput.length);
    }catch(IOException e){
        System.out.println(e.getMessage());
    }
}

Upvotes: 0

vhula
vhula

Reputation: 497

It's much better not to use an absolute path, but to place a file on the classpath and locate it using class loader:

InputStream fileIS = getClass().getClassLoader().getResourceAsStream("mombirthday.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(fileIS, writer, encoding);
String text = writer.toString();

Upvotes: 0

GhostCat
GhostCat

Reputation: 140407

The path that you give to that library call doesn't know or care about your project setup.

So, what you have right now points to the root of your file system. For starters you could change to an absolute path.

Upvotes: 0

Related Questions