- Goal: Print the data from a .dat file to the console using Eclipse.
- (Long-Term Goal): Executable that I can pass a .dat file to and it creates a new txt file with the data formatted.
The .dat: I know the .dat file contains control points that I will need to create a graph with using ECMAScript.
Eclipse Setup:
Created Java Project
New > Class .. called the Class FileRead
Now I have FileRead.java which is:
1/ package frp;
2/
3/ import java.io.BufferedReader;
4/ import java.io.File;
5/ import java.io.FileReader;
6/
7/ public class FileRead {
8/
9/ public static void main(String[] args) {
10/ FileReader file = new FileReader(new File("dichromatic.dat"));
11/ BufferedReader br = new BufferedReader(file);
12/ String temp = br.readLine();
13/ while (temp != null) {
14/ temp = br.readLine();
15/ System.out.println(temp);
16/ }
17/ file.close();
18/ }
19/
20/ }
Please note this approach was borrowed from here: https://stackoverflow.com/a/18979213/3306651
1st Challenge: FileNotFoundException on LINE 10
Screenshot of Project Explorer:
QUESTION: How to correctly reference the .dat file?
2nd Challenge: Unhandled exception type IOException LINES 12, 14, 17
QUESTION: How to prevent these exceptions?
Thank you for your time and effort to help me, I am recreating Java applets using only JavaScript. So, I'm looking to create java tools that extract data I need to increase productivity. If you are interested in phone/web app projects involving JavaScript, feel free to contact me 8503962891
I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.
To oversimplify, just wrap the file-handling code in a
try...catch
block. By example:Note that ideally, your
try...catch
should wrap the smallest possible unit of code. So, wrap theFileReader
separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its owntry...catch
. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.Edit: issue of file path
Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.
1. Without changing your code, you must place the file in the project's root folder. Otherwise, reference it as
src/frp/dichromatic.dat
2. Doing something like this:
3. Creation of a new txt file "formatted". In this example, the formatting will be settings the characters to uppercase.