Reading textfile into 2d array JAVA - java

I am trying to read a given text file filled with a bunch of doubles, the text file looks something like this(no spaces between each line):
0, 0.007133248, 0.003747135, 0.0034464097, 0.009517824, 0.0036065334,
0.007921185, 0.0041013476
1, 0.006223865, 5.804103E-4, 5.6967576E-4, 0.008850083, 0.003269921,
3.7322243E-4, 0.0011008179
2, 0.0051101227, 0.008973722, 0.0013274436, 0.00922496, 0.0050817304,
0.004631279, 0.0069321943
essentially 1000 rows with 8 columns, and am trying to turn this into a 2d array of data[1000][8], am having trouble iterating through the data though. Heres what I have so far, any help would be appreciated!
public static void readFile2() throws IOException{
Double[][] data = new Double[1000][8];
int row = 0;
int col = 0;
Scanner scanner = null;
scanner = new Scanner(new BufferedReader(new FileReader("/Users/Roman/Documents/workspace/cisc124/Logger (1).csv")));
while (scanner.hasNext() && scanner !=null) {
scanner.useDelimiter(",");
while(row<data.length && col<8){
data[row][col] = Double.parseDouble(scanner.next());
col++;
//System.out.print(Arrays.deepToString(data));
}
col=0;
row++;
}
System.out.println(Arrays.deepToString(data));
scanner.close();
}

It would be more convenient reading thefile line by line..
String[] data = new String[1000];
int row = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
data[row]= line;
row++;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
and at the end do the same
System.out.println(Arrays.ToString(data));
or if you need the element at a given index then split a row and use Double.parse();

Related

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

How to get text from a TextFile and putting it to a Table

I am trying to put text from a text file to a table I want it to display on the table when pressing a button. It does not display any errors it just does not work. Can someone please explain why and how to make it work. The text is divided with ;
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
int v =0;
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
Object[] row = new String[v];
do{
r = br.readLine();
if(r!=null){
for (int i = 0; i < v; i++) {
int ix = r.indexOf(";");
row[i] = r.substring(0, ix);
r = r.substring(ix+1);
int zn = r.indexOf(";");
row[i] += r.substring(0, zn);
r = r.substring(zn+1);
int xn = r.indexOf(";");
row[i] += r.substring(0, xn);
r = r.substring(xn+1);
int an = r.indexOf(";");
row[i] += r.substring(0, an);
table.addRow(row);
}
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
You should shorten this.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
do{
r = br.readLine();
if(r!=null){
String [] sline=r.split(";");
table.addRow(sline);
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
Reason: you read the file 2 times but without resetting the stream. Why?
Then you counted the number of lines and took this number as number of columns, why?
You count the number of lines in the file
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
After that you try to read from the file, after the EOF has already been reached
do{
r = br.readLine();
if(r!=null){
[...]
}
}while(r!=null);
r = br.readLine(); will return null, since the EOF has been reached, and skip over the loop
To fix this, you can either reopen the file
//counting code
br.close();
br = new BufferedReader([...]);
//reading code
Or you can add the lines to a List instead, and use that
BufferedReader br = new BufferedReader([...]);
List<String> lines = new ArrayList<String>();
for(String line = br.readLine(); line != null; line = br.readLine())
lines.add(line);
String[] row = lines.toArray(new String[0]);
If you're just adding the values to a table, it may be easier to not store the file at all
BufferedReader br = new BufferedReader([...]);
for(String line = br.readLine(); line != null; line = br.readLine())
table.addRow(line.split(";"));

How to read certain char to certain char from file in java?

I have a text file, which contains positions like this:
The #p shows the x, y coordinates, so the first * after the #p row is at (6, -1). I would like to read the text file as blocks (one block is from the #p to the next #p row).
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
if (line.startsWith("#P")){
Scanner s = new Scanner(line).useDelimiter(" ");
List<String> myList = new ArrayList<String>();
while (s.hasNext()) {
myList.add(s.next());
}
for (int i=0; i<myList.size(); i++){
System.out.println(myList.get(i));
}
System.out.println("xy: "+myList.get(1)+", "+myList.get(2));
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
I want to store the coordinates in a two dimensional array, but there goes my other problem. How can I store etc -1, -1?
This doesn't completely solve your problem, but one option here is to use a map to store each block of text, where a pair of coordinates is a key, and the text a value.
Map<String, String> contentMap = new HashMap<>();
String currKey = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#P")) {
// store previous paragraph in the map
if (currKey != null) {
contentMap.put(currKey, buffer.toString());
buffer = new StringBuffer();
}
currKey = line.substring(3);
}
else {
buffer.append(line).append("\n");
}
}
Once you have the map in memory, you can either use it as is, or you could iterate and somehow convert it to an array.
byte[][] coords = new byte[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1]; //your array with 0 and 1 as you wished
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//StringBuffer stringBuffer = new StringBuffer(); //i don't c why you need it here
String line;
while ((line = bufferedReader.readLine()) != null) {
//stringBuffer.append(line);
//stringBuffer.append("\n");
if (line.startsWith("#P")){
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
coords[x - X_MIN][y - Y_MIN] = 1;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Array indices in Java always start at 0. But that's not really a problem if you know the total ranges of your x and y values (X_MIN <= x < X_MAX and Y_MIN <= y < Y_MAX):
coor[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1];
...
void setValue( int x, int y, int value ) {
coor[x - X_MIN][y - Y_MIN] = value;
}
int getValue( int x, int y ) {
return coor[x + X_MIN][y + Y_MIN];
}
A nicer solution would wrap the array into a class, provide range checking and maybe use a different container like ArrayList<ArrayList<int>> .

java read only integers from file

If I have a file that contains for example:
results1: 2, 4, 5, 6, 7, 8, 9
results2: 5, 3, 7, 2, 8, 5, 2
I want to add the integers from each line to a array. One array
for each line. How can I do this with code that does only read the integers?
Here's what I got this far
String data = null;
try {
Scanner in = new Scanner(new File(myFile));
while (in.hasNextLine()) {
data = in.nextLine();
numbers.add(data);
}
in.close();
} catch (Exception e) {
}
Easy.
One line per array, not two as you have it. New line after each one.
Read each line as a String, discard the leading "resultsX:", and split what remains at a delimiter of your choosing (e.g. comma). Parse each into an integer and add it to a List.
I don't think that leading "results1: " is adding any value. Why do you have that?
public static void main(String[] args) throws IOException {
BufferedReader reader=null;
try {
reader = new BufferedReader(new FileReader(new File("PATH TO FILE")));
// Only works if File allways contains at least two lines ... all lines after the second
// will be ignored
System.out.println(String.format("Array 1 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
System.out.println(String.format("Array 2 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
} finally {
if (reader!=null) {
reader.close();
}
}
}
private static Integer[] stringArray2IntArray(String[] numStrings) {
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < numStrings.length; i++) {
result.add(Integer.parseInt(numStrings[i].trim()));
}
return result.toArray(new Integer[numStrings.length]);
}
private static String[] readNextLine(BufferedReader reader) throws IOException {
return reader.readLine().split(":")[1].split(",");
}
Assuming you have an input file, like this:
2,4,5,6,7,8,9
5,3,7,2,8,5,2
here is a code snippet to load it:
String firstLine = "";
String secondLine = "";
File file = new File("path/to/file");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
firstLine = br.readLine();
secondLine = br.readLine();
} catch(Exception e){
e.printStackTrace();
}
String[] firstResult = firstLine.split(",");
String[] secondResult = secondLine.split(",");
int[] firstIntegers = new int[firstResult.length];
for(int i = 0; i <= firstResult.length ; i++){
firstIntegers[i] = Integer.parseInt(firstResult[i]);
}
int[] secondIntegers = new int[secondResult.length];
for(int i = 0; i <= secondResult.length ; i++){
firstIntegers[i] = Integer.parseInt(secondResult[i]);
}
Open the file with a BufferedReader br and then read it line by line.
Store each line in an int array and add all those int arrays to a list. At the end, this list will contain all the int arrays that we wanted, so iterate this list to do whatever you want to do next.
String filePath = "/path/to/file";
BufferedReader br = null;
List<Integer[]> arrays = new ArrayList<>(); //this contains all the arrays that you want
try {
br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf(":")+2); //this starts the line from the first number
String[] stringArray = line.split(", ");
Integer[] array = new Integer[stringArray.length];
for (int i = 0; i < stringArray.length; ++i) {
array[i] = Integer.parseInt(stringArray[i]);
}
arrays.add(array);
}
} catch (FileNotFoundException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
Since ArrayLists keep insertion order, then, e.g., arrays.get(3) will give you the array of the fourth line (if there is such a line) and arrays.size() will give you the number of lines (i.e., int arrays) that are stored.

How to read N amount of lines from a file?

I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.
Say for example, the file contains 1-100 numbers, like so;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.
ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));
for (double i = 0; i <= 5; ++i) {
// I know I need to add something here so the for loop read through
// the file but I have no idea how I can do this
array.add(i); // This is saying read 1 line and add it to arraylist,
// then read read second and so on
}
You could try using a Scanner and a counter:
ArrayList<Double> array = new ArrayList<Double>();
Scanner input = new Scanner(new File("numbers.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 10)
{
array.add(Double.parseDouble(input.nextLine()));
counter++;
}
This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.
See this How to read a large text file line by line using Java?
I think this will work:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
if (i < 5)
{
// process the line.
i++;
}
}
br.close();
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
System.err.println(ex.toString());
//here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
//read line by line with the readLine() method
while ((line = reader.readLine()) != null && counter < N) {
//check also the counter if it is smaller then desired amount of lines to read
array.add(line); //add the line to the ArrayList of strings
counter++; //update the counter of the read lines (increment by one)
}
//the while loop will exit if:
// there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
// OR the desired amount of line was correctly read
reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
System.err.println(ex.toString());
}
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("numbers.txt")))) {
for (int i = 0; i < 5; ++i) { // Loops 5 times
String line = in.readLine();
if (line == null) [ // End of file?
break;
}
// line does not contain line-ending.
int num = Integer.parseInt(line);
array.add(i);
}
} // Closes in.
System.out.println(array);
You can do this with:
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
// do something with the list here
}
As complete example as JUnit test:
public class ReadFirstLinesOfFileTest {
#Test
public void shouldReadFirstTenNumbers() throws Exception {
Path p = Paths.get("numbers.txt");
Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
}
}
}
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
myList.add(fileScanner.nextDouble());
}
Make sure you have "numberOfLinesToRead" lines in your file.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> nlines = IntStream.range(0, hlines)
.mapToObj(i -> readLine(br)).collect(Collectors.toList());
String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

Categories