Read Double From a .txt File into an Array List - java

So we have this program where we have to read double values from a text file into a double ArrayList and make certain calculations.
example of the text file:
Note: there's space between the date and the double values
5/05/1998 4.4
1/01/1999 -4.123
the problem is that i'm getting is as below:
"NumberFormatException for input string: 1/2/1950 0.0258" error.
Here's my code:
public static void value() throws java.io.IOException{
try{
BufferedReader br = new BufferedReader(new FileReader(new File("SP500-Weekly.txt")));
ArrayList<Double>list = new ArrayList<Double>();
String line;
while((line=br.readLine())!=null){
String[] r = line.split(" ");
for(int i=0; i<r.length; i++){
double val = Double.parseDouble(r[i]);
list.add(val);
}
}br.close();
System.out.println(list.size());
}
catch(IOException io){
System.out.println("error");
}
}

Seems like you just need the double value present on each line and want to add it into a List<Double>. Based off of your input, second value is always your double value, but you are trying to parse first value as well which is a date and Double.parseDouble() cannot parse characters that comes in a date such as /, thus you ran into exception. If the double value is what you need then do it simply as :
try {
BufferedReader br = new BufferedReader( new FileReader( new File( "SP500-Weekly.txt"" ) ) );
List<Double> list = new ArrayList<Double>();
String line;
while ( ( line = br.readLine( ) ) != null ) {
String[] r = line.split( "\\s+" );
list.add( Double.parseDouble( r[ 1 ] ) );
}
br.close( );
System.out.println( list.size( ) );
} catch ( IOException io ) {
e.printStackTrace( );
}
You can then play around with list variable as your wish.
Also if you want to be more specific and check if it's actually number/double for second value then I'd do following to add a regex which will make sure that the second value is number (with or without - sign) as below:
while ( ( line = br.readLine( ) ) != null ) {
String[] r = line.split( "\\s+" );
for ( String string: r ) {
if ( string.matches( "^-?[0-9]?.?[0-9]+" ) ) {
list.add( Double.parseDouble( r[ 1 ] ) );
}
}
}

A very simple and up to date implementation of this using java.nio and pure Java 8 would the following.
private static List<Double> readDoubles(final String fileName) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.map(s -> s.split("\\s+")[1])
.map(Double::parseDouble)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}
Implementation also takes the liberty of using try-with-resources to auto manager the various resources.

CORRECTCODE:
import java.util.List;
class Sample extends SimulateMarket{
public static void value(){
try{
BufferedReader br = new BufferedReader(new FileReader(new File("SP500-Weekly.txt")));
List<Double> list = new ArrayList<Double>();
String line;
while((line=br.readLine())!=null){
String[] r = line.split("\\s+");
list.add(Double.parseDouble(r[1]));
}br.close();
Random rand = new Random();
int randomIndex = rand.nextInt(list.size());
System.out.println(list.get(randomIndex));
}
catch(IOException io){
System.out.println("error");
}
}
}

Related

Wrong value while getting the triple duplicate

I have developed a java code that takes a text file as input and selects the duplicate words and gives output by creating a new text file containing the duplicate words, now I need it to select triple duplicated words, but i cannot get it correctly. below is my java code-
import java.util.*;
import java.io.*;
public class CheckDuplicate {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FileReader file1=new FileReader("/home/goutam/workspace/DuplicateWord/clean_2014.txt");
BufferedReader reader1=new BufferedReader(file1);
File f=new File("Reduplication.txt");
FileWriter fw=new FileWriter(f);
String line=reader1.readLine();
while(line!=null){
String[] arr=line.split(" ");
if(arr.length>1){
for(int i=0;i<arr.length;i++){
if(i<arr.length-1){
int cmp=arr[i].compareTo(arr[i+1]);
if(cmp==0){
fw.write(arr[i].toString());
fw.write("\n");
}
}
}
}
line=reader1.readLine();
}
reader1.close();
file1.close();
}
}
Your code doesn't work because you're only considering adjacent elements.
Instead of having nested loops, you can achieve what you want easily using Map that String as a value and an integer that indicates the count as the value.
When you first encounter a string, you insert it with a value of 1
When you have a string that's already in the map, you simply increment its value
Then you can iterate on the values and pick the keys with value > what you want.
I highly recommend you using the debugger, it helps you better understanding the flow of your program.
This should do the job, note: I did not compile nor test it but at least it should provide you some directions.
public void findRepeatingWords( int atLeastNRepetitions ) {
try ( BufferedReader reader1 = new BufferedReader( new FileReader("/home/goutam/workspace/DuplicateWord/clean_2014.txt") ) ) {
// There are libraries that can do this, but yeah... doing it old style here
// Note that usage of AtomicInteger is just a convenience so that we can reduce some lines of codes, not used for atomic operations
Map<String, AtomicInteger> m = new LinkedHashMap<String, AtomicInteger>() {
#Override
public AtomicInteger get( Object key ) {
AtomicInteger cnt = super.get( key );
if ( cnt == null ) {
cnt = new AtomicInteger( 0 );
super.put( key, cnt );
}
return cnt;
}
};
String line = reader1.readLine();
while( line!=null ){
// Note we use \\W here that means non-word character (e.g. spaces, tabs, punctuation,...)
String[] arr = line.split( "\\W" );
for ( String word : arr ) {
m.get( word ).incrementAndGet();
}
line = reader1.readLine();
}
}
}
private void writeRepeatedWords( int atLeastNRepetitions, Map<String, AtomicInteger> m ) {
File f = new File( "Reduplication.txt" );
try ( PrintWriter pw = new PrintWriter( new FileWriter( f ) ) ) {
for ( Map.Entry<String, AtomicInteger> entry : m.entrySet() ) {
if ( entry.getValue().get() >= atLeastNRepetitions ) {
pw.println( entry.getKey() );
}
}
}
}
Here is the thing you are searching for, I have performed it using LinkedHashMap, It's a dynamic code, you select not only double, triple but also go for n number of time.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class A3 {
public static void main(String[] args) throws IOException {
BufferedReader reader1 = new BufferedReader(new java.io.FileReader(
"src/Source/A3_data"));
PrintWriter duplicatewriter = new PrintWriter(
"src/Source/A3_out_double", "UTF-8");
PrintWriter tripleduplicatewriter = new PrintWriter(
"src/Source/A3_out_tripple", "UTF-8");
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
String line = reader1.readLine();
while (line != null) {
String[] words = line.split(" ");
int count = 0;
while (count < words.length) {
String key = words[count];
Integer value = map.getOrDefault(key, 0) + 1;
map.put(key, value);
count++;
}
line = reader1.readLine();
}
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 2)
duplicatewriter.println(entry.getKey());
if (entry.getValue() == 3)
tripleduplicatewriter.println(entry.getKey());
}
duplicatewriter.close();
tripleduplicatewriter.close();
}
}
Since you want the items to appear 3 times in a row, I modified my code to achieve your goal:
public static void main(String[] args) throws Exception {
FileReader file1 = new FileReader("/home/goutam/workspace/DuplicateWord/clean_2014.txt");
BufferedReader reader1 = new BufferedReader(file1);
File f = new File("Reduplication.txt");
FileWriter fw = new FileWriter(f);
String line = reader1.readLine();
while (line != null) {
String[] arr = line.split(" ");
if (arr.length > 1) {
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 2) { // change from length-1 to length-2
int cmp = arr[i].compareTo(arr[i + 1]);
if (cmp == 0) {
if (arr[i + 1].equals(arr[i + 2])) { // keep comparing the next 2 items
System.out.println(arr[i].toString() + "\n");
fw.write(arr[i].toString());
fw.write("\n");
}
}
}
}
}
line = reader1.readLine();
}
reader1.close();
file1.close();
}
Try This this code print if count is greater than 3 you can use any number
public static void getStringTripple(String a){
String s[]=a.split(" ");
List<String> asList = Arrays.asList(s);
Set<String> mySet = new HashSet<String>(asList);
for(String ss: mySet){
if(Collections.frequency(asList,ss)>=3)
System.out.println(ss + " " +Collections.frequency(asList,ss));
}
}

Read lines from a .txt to a table of objects

I need help; what I'm trying to do is to put each line of a text file into an table of object.
Let's get into example :
I have that text file:
ATI
8
10
AMX
12
15
As we can see, this text file contain different types of mother boards.
So I have this constructor (which is on another class) of mother boards objects:
motherBoard(String type, int size, int max_size){
this.type = type;
this.size = size;
this.max_size = max_size;
}
So what I'm trying to do is to make a table of object where (in this example) the first object of the table would contain the 3 first lines of the text file. Then, the 2nd object of the table would contain the next 3 lines so on...
All the operations I want to do are in a method...
Here is my code so far :
public static CarteMere[] chargerEnMemoire(String nomFichier) throws IOException{
CarteMere[] newCarteMere = new CarteMere[0];
try {
FileReader reader = new FileReader( "liste.txt" );
BufferedReader buffer = new BufferedReader( reader );
int nmLines = 0;
while ( buffer.ready() ) {
nmLines++; // To evaluate the size of the table
}
buffer.close();
newCarteMere = new CarteMere[nmLines/3];
for(int i=0; i<(nmLines/3);i++){
}
} catch ( FileNotFoundException e ) {
System.out.println( e.getMessage() );
} catch ( IOException e ) {
System.out.println( e.getMessage() );
}
return newCarteMere;
}
That's where I need a push...
Start with what you know, you have a file, it contains data in groups of three lines, one's a String, the other two are numbers.
You have a class which represents that data, always easier to store data in an object where possible, so you could do something like...
try (BufferedReader br = new BufferedReader(new FileReader("liste.txt"))) {
String name = br.readLine();
int size = Integer.parseInt(br.readLine());
int max = Integer.parseInt(br.readLine());
Motherboard mb = new MotherBoard(name, size, max);
// Add it to a List or what ever else you want to do it...
} catch (IOException exp) {
exp.printStackTrace();
}
In case you have getter and setter for all 3 variables in your pojo class and you have overloaded toString() method in motherBoard class,
Integer noOfLines=0, i=0, j=0;
String [] data=null;
String sCurrentLine=null;
BufferedReader br = new BufferedReader(new FileReader("liste.txt"));
while ((sCurrentLine = br.readLine()) != null)
{
noOfLines++;
data[i]=sCurrentLine;
}
i=-1;
j=noOfLines/3;
motherBoard mb=null;
for(int x=0;x<=j;x++)
{
mb=new motherBoard(data[++i], Integer.parseInt(data[++i]), Integer.parseInt(data[++i]))
System.out.println(mb);
}
Regarding just reading the data from a file and loading it into classes, hopefully this example will help you:
MotherBoard.java
public class MotherBoard {
String type;
int size;
int max_size;
public MotherBoard (String type, int size, int max_size) {
this.type = type;
this.size = size;
this.max_size = max_size;
}
public String toString() {
return "Motherboard data : type=" + type + " size=" + size + ", max_size=" + max_size;
}
}
Solution.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Solution {
public static void main(String[] args) {
try {
FileReader reader = new FileReader( "liste.txt" );
BufferedReader buffer = new BufferedReader( reader );
int nmLines = 0;
int numMBs = 0;
while (buffer.ready()) {
numMBs++;
/* Not a good approach if your data isn't perfect - just an example for StackOverflow */
MotherBoard mb = new MotherBoard (buffer.readLine(),
Integer.parseInt(buffer.readLine()),
Integer.parseInt(buffer.readLine()));
System.out.println("Motherboard " + numMBs + ":");
System.out.println(mb.toString());
}
/* Probably want to do this in a finally block too */
buffer.close();
reader.close();
} catch ( FileNotFoundException e ) {
System.out.println( e.getMessage() );
} catch ( IOException e ) {
System.out.println( e.getMessage() );
}
}
}
To compile and run:
javac -cp . MotherBoard.java Solution.java
java Solution
Output:
Motherboard 1:
Motherboard data : type=ATI size=8, max_size=10
Motherboard 2:
Motherboard data : type=AMX size=12, max_size=15
So i found a way... I think i found a solution...
Here is my new code :
public static CarteMere[] chargerEnMemoire(String nomFichier) throws IOException{
CarteMere[] newCarteMere = new CarteMere[0];
try {
FileReader reader = new FileReader( nomFichier );
BufferedReader buffer = new BufferedReader( reader );
int nmLines = 0;
while ( buffer.readLine() != null) {
nmLines++; // To evaluate the size of the table
}
buffer.close();
reader.close();
//RESET THE BUFFER AND READER TO GET ON TOP OF THE FILE
FileReader reader2 = new FileReader( nomFichier );
BufferedReader buffer2 = new BufferedReader( reader2 );
newCarteMere = new CarteMere[nmLines/3];
for(int i=0; i<(nmLines/3);i++){
int forme = CarteMere.chaineFormeVersCode(buffer2.readLine());
int mem_inst = Integer.parseInt(buffer2.readLine());
int mem_max = Integer.parseInt(buffer2.readLine());
newCarteMere[i] = new CarteMere(forme, mem_inst, mem_max);
}
buffer2.close();
reader2.close();
} catch ( FileNotFoundException e ) {
System.out.println( e.getMessage() );
} catch ( IOException e ) {
System.out.println( e.getMessage() );
}
return newCarteMere;
}
But the idea of reseting the buffer and redear like that seems ugly to me... Do you guys have an idea to do the same sime but more correctly ?
Thank in advance

Count the number of lines from point A to point B in Text File

I am trying to figure out how to find the first instance of a string in a given text file, start counting the number of lines starting from the first line with that instance of the string, then stop counting when another/different string is found in a new line.
Basically I have a text file like:
CREATE PROCEDURE "dba".check_diff(a smallint,
b int,
c int,
d smallint,
e smallint,
f smallint,
g smallint,
h smallint,
i smallint)
RETURNING int;
DEFINE p_ret int;
LET p_ret = 0;
END IF;
RETURN p_ret;
END PROCEDURE;
And I just want to find the first instance of "CREATE PROCEDURE" and increment a variable until I reach the instance of "END PROCEDURE;", then reset the variable.
What I have been trying is...
import java.io.*;
public class countFile
{
public static void main(String args[])
{
try
{
int i = 0;
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:/results.txt");
// Stream to write file
FileOutputStream fout = new FileOutputStream("C:/count_results.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
if (strLine.contains("CREATE PROCEDURE"))
{
while (!strLine.contains("END PROCEDURE;"))
{
i++;
break;
}
new PrintStream(fout).println (i);
}
}
//Close the input stream
in.close();
fout.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
However, that just counts the total number of instances of "CREATE PROCEDURE" and writes out the variable i each time it gets incremented...not what I'm looking for.
Any help?
SOLUTION FOUND:
import java.io.*;
public class countFile
{
public static void main(String args[])
{
try
{
int i = 0;
boolean isInProcedure = false;
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:/results.txt");
// Stream to write file
FileOutputStream fout = new FileOutputStream("C:/count_results.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// If the line contains create procedure...
if (strLine.contains("CREATE PROCEDURE"))
{
// Set this flag to true
isInProcedure = true;
}
// If the line contains end procedure, stop counting...
if (strLine.contains("END PROCEDURE;"))
{
// Write to the new file
new PrintStream(fout).println(i);
// Set flag to false
isInProcedure = false;
// Reset counter
i = 0;
}
// Used to count lines between create procedure and end procedure
else
{
if (isInProcedure == true)
{
//Increment the counter for each line
i++;
}
}
}
//Close the input stream
in.close();
fout.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try this:
while (br.ready()) {
if (br.readLine().contains("CREATE PROCEDURE")) {
while (!br.readLine().contains("END PROCEDURE;")) {
i++;
}
}
new PrintStream(fout).println(i);
i = 0;
}
import java.io.BufferedReader;
import java.io.FileReader;
public class Test
{
public static void main( String args[] )
{
try
{
BufferedReader bufferedReader = new BufferedReader( new FileReader( "c:\\test.txt" ) );
String line;
Boolean count = false;
Integer lines = 0;
while ( ( line = bufferedReader.readLine() ) != null )
{
if ( line.toUpperCase().contains( "CREATE PROCEDURE" ) )
{
count = true;
}
if ( line.toUpperCase().contains( "END PROCEDURE;" ) )
{
break;
}
if ( count == true )
{
lines++;
}
}
System.out.println( lines );
}
catch ( Exception exception )
{
exception.printStackTrace();
}
}
}

Split a String in an ArrayList depending on selected amount of characters

I'd like to split a string into an ArrayList.
Example:
String = "Would you like to have responses to your questions"
result with amount 3: Wou -> arraylist, ld -> arraylist, you -> arraylist, ...
the amount is a predefined variable.
so far:
public static void analyze(File file) {
ArrayList<String> splittedText = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
splittedText.add(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String wholeString = buf.toString();
wholeString.substring(0, 2); //here comes the string from an txt file
}
The "normal" way to do it is about what you'd expect:
List<String> splits = new ArrayList<String>();
for (int i = 0; i < string.length(); i += splitLen) {
splits.add(string.substring(i, Math.min(i + splitLen, string.length()));
}
I'll throw out a one-line solution with Guava, though. (Disclosure: I contribute to Guava.)
return Lists.newArrayList(Splitter.fixedLength(splitLen).split(string));
FYI, you should probably use StringBuilder instead of StringBuffer, since it doesn't look like you need thread safety.
You can do it without substring calls like this:
String str = "Would you like to have responses to your questions";
Pattern p = Pattern.compile(".{3}");
Matcher matcher = p.matcher(str);
List<String> tokens = new ArrayList<String>();
while (matcher.find())
tokens.add(matcher.group());
System.out.println("List: " + tokens);
OUTPUT:
List: [Wou, ld , you, li, ke , to , hav, e r, esp, ons, es , to , you, r q, ues, tio]
You are adding each line to your array list, and it doesn't sound like that is what you want. I think you are looking for something like this:
int i = 0;
for( i = 0; i < wholeString.length(); i +=3 )
{
splittedText.add( wholeString.substring( i, i + 2 ) );
}
if ( i < wholeString.length() )
{
splittedText.add( wholeString.substring( i ) );
}

Find a specific line of a text file (not by line_number) and store it as a new String

I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
public class ReadFile {
private String path;
public ReadFile (String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader (path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//textData[i] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader (path);
BufferedReader bf = new BufferedReader (file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null ) {
numberOfLines ++;
}
bf.close ();
return numberOfLines;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..

Categories