Here is what I am trying to do, say I have an input file (input.txt) in this format, the number of rows or columns can be different, columns are separated by spaces:
the DT B-NP
current JJ I-NP
account NN I-NP
deficit NN I-NP
will MD B-VP << CURRENT TOKEN
narrow VB I-VP
to TO B-PP
only RB B-NP
I want to get each word into an element of a 2 dimension array x[i,j] so that, I can use an index file:
x[0,0]
x[0,1]
x[-1,0]
x[-2,1]
to get this result:
will
MD
deficit
NN
With the number in the bracket is the i,j index of the array, the starting position [0,0] is the first word of the line that marked by "<< CURRENT TOKEN" (in this case is word "will" ).
So now I can read the file to array by:
import java.awt.List;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadfileIntoArray {
String[] data = new String[100];
public void read() throws IOException {
FileReader fr = new FileReader("/Users/home/Documents/input.txt");
BufferedReader br = new BufferedReader(fr);
String line;
System.out.println("Print from here:");
int i = 0;
while ((line = br.readLine()) != null) {
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
// This is for resize the data array (and data.length reflect new size)
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
public static void main(String[] args) throws IOException {
ReadfileIntoArray rfta = new ReadfileIntoArray();
rfta.read();
}
}
But as I searched, I might need to use
List<String> arrList =FileUtils.readLines(new File("myfile.txt"));
for undefined length (??) not very sure but I think need to import special package to use it, I got error _ Second thing is how to determined the starting element at position [0,0], and how to indicate negative index like [-2,1]...
How can I managed to do the task above, it look quite complicated for me. Thanks alot !