Programming43343443 Programming43343443 - 4 months ago 17
Java Question

Simple java file reader not working

I am creating a program where two numbers are read from one file (test.in) and then the sum is output to another file (test.out). I created the two files as TXT documents in the bin folder of my project but it still gives this

Exception in thread "main" java.io.FileNotFoundException: test.in.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at test.main(test.java:11)


The files are not showing up in my project directory on the left hand side of the screen, it just won't work.

import java.io.*;
import java.util.*;

public class test {
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("test.in.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));
StringTokenizer st = new StringTokenizer(f.readLine());
int i1 = Integer.parseInt(st.nextToken()); // first integer
int i2 = Integer.parseInt(st.nextToken()); // second integer
out.println(i1+i2); // output result
out.close(); // close the output file
}
}

Answer

As you can see your file is an textdocument, so it ends with ".txt" even if you can't see it in the folder!

You have to change "test.in" and "test.out" into "test.in.txt" and "test.out.txt"

import java.io.*;
import java.util.*;

public class test {
    public static void main (String [] args) throws IOException {
        BufferedReader f = new BufferedReader(new FileReader("test.in.txt"));
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));
        StringTokenizer st = new StringTokenizer(f.readLine());
        int i1 = Integer.parseInt(st.nextToken());    // first integer
        int i2 = Integer.parseInt(st.nextToken());    // second integer
        out.println(i1+i2);                           // output result
        out.close();                                  // close the output file
      }
}