Goal: Get the data from a .dat file and print it to the console in Eclipse
Resources: fpfret.java and PointF.java and dichromatic.dat
I have resolved all my issues and have just a few console errors, here's my code and my question is: How do I add the getCodeBase() method?
package frp3;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.net.URL;
import java.util.Vector;
public class FileRead {
public static void main(String[] args) { //getDocumentBase
System.out.println(readDataFile(getCodeBase() + "dichromatic.dat", 300, 750));
}
private static String getCodeBase() {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("unchecked")
private static PointF[] readDataFile(String filename, int min, int max) {
@SuppressWarnings("rawtypes")
Vector v = new Vector();
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream((new URL(filename)).openStream()));
float f0, f1;
while (true) {
try {
f0 = dis.readFloat();
f1 = dis.readFloat();
if (min < 0 || max < 0 || (f0 >= min && f0 <= max)) {
v.addElement(new PointF(f0, f1));
}
}
catch (EOFException eof) {
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
PointF[] array = new PointF[v.size()];
for (int i = 0; i < v.size(); i++) {
array[i] = (PointF) v.elementAt(i);
}
return array;
}
}
Here's my console errors:
java.net.MalformedURLException: no protocol: nulldichromatic.dat
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at frp3.FileRead.readDataFile(FileRead.java:27)
at frp3.FileRead.main(FileRead.java:12)
[Lfrp3.PointF;@29be513c
Here's my Project View in Eclipse:
Alright. This is actually more complex then I thought at first pass. Basically, readDataFile expects the dichromatic.dat file to be a resource available on the Internet. Look at the following line from readDataFile:
Basically, whatever filename gets passed in, is used as a URL. For your use-case, where your file is hosted on your local filesystem, I recommend a few changes.
First, replace the above DataInputStream declaration line with:
Second, replace getCodeBase with:
I've simply replace null with an empty string. Since "dichromatic.dat" is in the root of your project, it should be sufficient to use an empty string, indicating project root, as the result for getCodeBase(), as the result of that function gets pre-pended to "dichromatic.dat" before being passed to readDataFile as
filename
.If you put dichromatic.dat in a different place, just modify that empty string to be the "path" that leads to the file.
Hope this helps.
Forgot to mention -- be sure to update your imports list to include
import java.io.FileInputStream
-- although Eclipse should handle this gracefully for you.