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
Related
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");
}
}
}
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));
}
}
I have got two text files with data in the following format
data.txt file as following format
A 10
B 20
C 15
data1.txt file is in format (start node,end node, distance):
A B 5
A C 10
B C 20
I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (i.e. I dont need the distance). I need to store this information in a stack as I think it would be a best data structure for implementing greedy search.
Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. So I would highly appreciate any starting idea on how to proceed.
I am new to this, so please bear with me. Any help is much appreciated. Thanks.
EDIT:
Here is what I have got till now
String heuristic_file = "data.txt";
try
{
FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}
bufferReader.close();
} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
My approach, doesn't differ fundamentally from the others. Please regard the try/catch/finally blocks. Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file.
The part between the two //[...] could surely be done more efficient. Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? Maybe a Stream-API supports to set the reading position. I honestly don't know. I didn't need that, up to now.
I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice.
Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed.
public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);
if (datafile1.exists())
{
BufferedReader r = null;
try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);
String row;
Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;
while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }
// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}
// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]
String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);
// [...parse firstrow and lastrow into a datastructure...]
}
}
use split
while ((line = bufferReader.readLine()) != null)
{
String[] tokens = line.split(" ");
System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
}
if you must have this in an array you can use the following:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class NodeTest {
public static void main(String[] args) throws ParseException {
try {
File first = new File("data.txt");
File second = new File("data1.txt");
Node[] nodes1 = getNodes(first);
Node[] nodes2 = getNodes(second);
print(nodes1);
print(nodes2);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public static final void print(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
public static final Node[] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List<Node> list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]);
}
}
class Node {
String start;
String end;
public Node(String start, String end){
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + "][" + end + "]";
}
}
Something like this?
HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
nodes.add(l[0]);
line = br.readLine();
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
if (nodes.contains(l[0]) || nodes.contains(l[1]))
// Do whatever you want ...
line = br.readLine();
}
}
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();
}
}
}
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..