Read from a file in Java - java

Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}

I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].

You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.

Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}

EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}

File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

Related

How do I store the CSV file data into an array in Java?

Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123

I am working on a program that checks the spelling of a txt file using a given dictionary in java. I am not getting the right outputs

I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}

How to find smallest value(from values given in a txt file) using BufferedReader in java

I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}

JAVA Filling a 2D array from a file with an unknown amount of rows

I am trying to figure out how to make a program that reads data from a text file, and fills a Jtable with it, I will need to be able to search the table, and do some calculations with the numbers.
A row in the text file would contain:
name, country, gender, age, weight
The number of rows is unknown (I need to count the number of rows).
This is what I tried, but it seems to crash. I need to count the # of rows, and then fill the array with the content from the rows.
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()){rows++;}
Object[][] data = new Object[rows][5];
System.out.print(rows);
file.nextLine();
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
}
change your code as follows
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
try{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine())
{
rows++;
file.nextLine();
}
file = new Scanner (new File("data.txt"));
System.out.println(rows);
Object[][] data = new Object[rows][5];
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
You create an array with 0 rows and then you try to access the empty array dimension.
Also I suppose you should reset the pointer of the scanner after counting the rows.
ArrayList should be more useful for your goal.
class Person {
String name, country, gender;
int age;
double weight;
public Person(String n, String c, String g, int a, double w) {
name = n;
country = c;
gender = g;
age = a;
weight = w;
}
}
Would properly model your data better when you are extracting from the file (I took a guess at Person but call it what you will). We then use ArrayList like so:
public static void main (String[] args) throws IOException {
ArrayList<Person> people = new ArrayList<Person>();
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()) {
String str = file.nextLine();
String[] tokens= str.split(",");
people.add(new Person(tokens[0], tokens[1], tokens[2],
Integer.parseInt(tokens[3], Double.parseDouble(tokens[4]))));
}
file.close();
Person[] arrayPeople = people.toArray();
}
ArrayLists are far more powerful than arrays as you can perform all sorts of operations on them like sorts and searches and of course you don't have to worry about their initial size because they just grow as you add new elements.
Maroun is right, you really need to use some Collections to help you with that :
public static void main(String[] args) throws Exception {
List<String[]> lines = readFiles(new File("data.txt"));
String[][] data = lines.toArray(new String[0][]);
}
public static List<String[]> readFiles(File file) {
List<String[]> data = new LinkedList<>();
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split(",");
data.add(tokens);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return data;
}
Note that you can use some third party libraries like Commons IO to read the file's lines :
List<String> lines = org.apache.commons.io.FileUtils.readLines(new File("data.txt"));)
Less code = less bugs!
Hope it helps
Move this line
Object[][] data = new Object[rows][5];
below
System.out.print(rows);
But as per answers above, we suggest change the code to use array lists if possible.

Converting CSV File to Java - Copied in Backwards

I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here

Categories

Resources