Sebastian Irimescu Sebastian Irimescu - 1 year ago 57
Java Question

FileNotFoundException with FileInputStream even though .getResource(filename) finds it

This is the first question I ask on stackoverflow, so if you notice something unpleasant/bad/inappropriate in my question, please be kind and point it out to me.

I have tried doing my school homework in Java, because I was tired of C++ and I had already done something in Python. However, I've had problems with reading from a binary file (which should contain one double and two float numbers, in order).


finds the file, but when I open a
public static Integer Leggere(Dati [] dato, String nomefile)
), it throws

This is my code:

import java.util.*;

public class Main{
public static void main(String[] args) {
Dati [] data = new Dati[23500];
int contatore = 0;
for(; contatore < 23500; contatore++){
data[contatore] = new Dati(0, 0, 0);
contatore = 0;

String path = Dati.class.getClassLoader().getResource("valori.bin").getPath().toString();
contatore = Leggere(data, path);
Acquisire(data, contatore);
Scrivere(data, "risultati.txt", contatore);

public static Integer Leggere(Dati [] dato, String nomefile){
int j = 0;
DataInputStream in = new DataInputStream(new FileInputStream(nomefile));
while(in.available() > 0){
dato[j].dato1 = in.readDouble();
dato[j].dato2 = in.readFloat();
dato[j].dato3 = in.readFloat();
catch(IOException e){
System.out.println("Problemi nell'apertura del file");

return j;

public static void Scrivere(Dati [] dato, String nomefile, int count){
PrintWriter output;
try {
output = new PrintWriter(nomefile);

Integer j = 0;
while(j < count){

} catch (FileNotFoundException e) {


public static void Acquisire(Dati [] dato, int count){
Scanner cinput = new Scanner(;
double c = 0.0;
int j = 0;

System.out.println("Inserisci un fattore di conversione: ");
while(c == 0.0){
c = cinput.nextDouble();

while(j < count){
dato[j].dato1 *= c;
dato[j].dato2 *= c;
dato[j].dato3 *= c;


The program ends with two messages, which handle the exception. The second one is the path of the file as found by the

Problemi nell'apertura del file

I know that it's a
because it says so in debug mode.

How would you have done this piece of code? Do you know what the problem is? Could you post an example to fix the problem or an example of an alternative method to cope with it?

Answer Source

You might want to take a look at the getResourceAsStream method in the class loader. It gives you an input stream that you can plug directly and not have to deal with full paths and those kinds of problems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download