hi james

Been a while since I have been here. am trying to do this program for the longest while. I have tried read and writing to a text file in java and i am getting a runtime error. can someone tell me where and why I am getting the runtime error. here is the codes that I have used.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author luanataylor
 */
public class NewFile {

    /**        

     * @param args the command line arguments
     */
    public static void main(String[] args) throws  IOException{

       StringBuilder sb = new StringBuilder();
       File f = new File("file.txt");

       BufferedReader br = null;

       try{

           br = new BufferedReader(new FileReader("file.txt"));

           String line;
           while((line = br.readLine()) != null){
                if(sb.length() > 0){
                    sb.append("\n");
                }
                sb.append(line);
           }

       }
       catch(IOException e){
           e.printStackTrace();
       }
       finally {

           try{

               if(br != null){
                   br.close();
               }
           }
           catch(IOException ex){
               ex.printStackTrace();
           }
       }
       String contents = sb.toString();
        System.out.println(contents);

 }
}
    here is the error

    java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at newfile.NewFile.main(NewFile.java:36)

BUILD SUCCESSFUL (total time: 0 seconds)

90% probability that it's just looking in the wrong place.
You can try
System.out.println(new File("file.txt").getAbsolutePath());
to see exactly where Java is expecting to find it.

ps this is a good place to use a try-with-resources, which will handle disposing of the reader regardless of errors, thus allowing you to omit the whole finally block (lines 39-50)

       try(BufferedReader br = new BufferedReader(new FileReader("file.txt"));) 
       {
           String line;
           while((line = br.readLine()) != null){
                if(sb.length() > 0){
                    sb.append("\n");
                }
                sb.append(line);
           }
       }
       catch(IOException e){
           e.printStackTrace();
       }

see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.