word word
word word

Reputation: 457

Java reading file and storing text as array

I wrote a program someone told me to do for reading file and storing the text as an array, but when I run the program, I get an error that looks like this:

run:
Exception in thread "main" java.io.FileNotFoundException: KeyWestTemp.txt (No such file                or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at HeatIndex.main(HeatIndex.java:32)

Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

I want to have my program display the array to make sure it works correctly. Any help would be greatly appreciated.

Below is the program code:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class HeatIndex {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException{
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");

    // create List
    List<String> temps = new LinkedList<String>();

    // while loop
    while(inFile1.hasNext()){

        // find next line
        token1 = inFile1.next();

        // initialize temps
        temps.add(token1);
    }

    // close inFile1
    inFile1.close();

    // create array
    String[] tempsArray = temps.toArray(new String[0]);

    // for-each loop
    for(String s : tempsArray){

        // display s to make sure program works correctly
        System.out.println(s);
    }
}

}

Upvotes: 1

Views: 1632

Answers (3)

Cosmin SD
Cosmin SD

Reputation: 1587

Apparently, the file KeyWestTemp.txt is not found by the Java program. The most likely problem is that you haven't placed it in the right place.

You have 2 options:

  1. Place the file in the working directory, from where you run the java command
  2. When initializing the Scanner, set the full path: new Scanner(new File("/file/path/to/KeyWestTemp.txt")) to the file

Upvotes: 1

Juan Luis
Juan Luis

Reputation: 3357

Two ways to fix it:

  1. Put your txt file in the same dir of your Java program.
  2. Write the full path of the txt file (c:/files...). Remember to use File.separator instead of the "/" or "\" to make the program platform independent.

Upvotes: 0

Tyler Lee
Tyler Lee

Reputation: 2785

Your program is unable to locate your file. Make sure the file is in your working directory, or change new File("KeyWestTemp.txt") to provide a complete path (e.g. C:/Users/...../KeyWestTemp.txt).

Upvotes: 2

Related Questions