How to get a specific value from a text file - java

I have a .txt file:
80,90,100,110,120,130,140,150,160
100,20,22,24,26,28,26,28,29,27
110,30,32,34,36,37,39,37,39,40
120,40,41,42,44,45,46,48,47,49
which represents a table with prices for blinds, the first row is the width of the blind and the first column without 80 is the height. The rest of the numbers are the prices.
I already did this using c# but in java I have no idea what to do, in c# my code looks like this and everything is fine. Can somebody show me the same thing in java?
theWidth and theHeight are text fields where I have to type the dimensions.
string[] lines = File.ReadAllLines(#"tabel.txt");
string[] aux = lines[0].Split(',');
for (int i = 0; i < aux.Length-1; i++)
{
if (aux[i] == theWidth.ToString())
{
Console.WriteLine(aux[i]);
indiceLatime = i;
}
}
for (int i = 1; i < lines.Length; i++)
{
aux = lines[i].Split(',');
if (aux[0] == theHeight.ToString())
{
showPrice.Text = aux[indiceLatime + 1];
}
}
In java I tried something like this:
try {
BufferedReader inputStream = new BufferedReader(new FileReader("tabel.txt"));
int theWidth = 90;
int theHeight = 100;
int indiceLatime = 0;
String line;
try {
while ((line = inputStream.readLine()) != null) {
String[] aux = line.split(",");
for (int i = 0; i < aux.length; i++) {
if (aux[i].equals(Integer.toString(theWidth))) {
indiceLatime = i;
}
}
for (int i = 1; i < aux.length; i++) {
if (aux[0].equals(Integer.toString(theHeight))) {
System.out.println("price: " + aux[indiceLatime]);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So the price is in theHeight's row of theWidth's index which I am trying to get somehow. Is there somebody who can show me how can I get the correct number(price) out from the row?

You can use FileReader like this:
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
// code here to handle the current readed line
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[Edit]
Regarding to your updates, i have edit you code, please check it.
int widthIndex = 90;
int hightIndex = 100;
int indiceLatime = 0;
boolean lookForWidth = true;
try {
BufferedReader br = new BufferedReader(new FileReader("table.txt"));
String line = "";
while ((line = br.readLine()) != null) {
String[] aux = line.split(",");
if(lookForWidth) {// this flag to look for width only at the first time.
for (int i = 0; i < aux.length; i++) {
if(widthIndex == Integer.parseInt(aux[i].trim())) {
indiceLatime = i;
lookForWidth = false;
continue;
}
}
}
for (int i = 0; i < aux.length; i++) {
if(hightIndex == Integer.parseInt(aux[0])) {
System.out.println(aux[indiceLatime]);
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Try like this:
public static void main(String[] args) throws FileNotFoundException {
String filePath = <Your file Path>;
try {
BufferedReader br = new BufferedReader(new FileReader(filePath ));
String line = br.readLine();
System.out.println(line);
while (line != null || !line.equals(null)) {
System.out.println(line);
line=br.readLine();
}
} catch (Exception e) {
}
}

Related

How to read a specific column of a row from a csv file in java

I have the following code which reads the data from the csv file, it iterates over the rows but i don't manage to figure out how to iterate over specific columns (for example the first 2 columns of that row) in order to find the data. Any suggestions?
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(String index:row) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
I understand that "," is your delimiter so the key is in the algorithm :
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(int i = 0; i < row.length; i++) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
if(i < 2){
System.out.println(i+" -> "+row[i]);
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}

How return a multidimensional arrayList in java?

I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{
public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE
public List<List<String>> fillArray(List<List<String>> array){
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++){
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
return array;
}
A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for (int i = 0; i < splited.length; i++) {
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
BTW: You should really use try with resources - it is much clearer.
Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;
public class Main {
public static List<List<String>> array2D = new ArrayList<List<String>>();
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
String str = "Some test text";
InputStream is = new ByteArrayInputStream(str.getBytes());
//in = new BufferedReader(new FileReader("sampleFile.txt"));
in = new BufferedReader(new InputStreamReader(is));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++) {
row.add(splited[i]);
}
array.add(row);
}
}
catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return array;
}
public static void main(String[] args) {
Main main = new Main();
List<List<String>> test = main.fillArray(array2D);
for(int i = 0; i < test.size(); i++) {
for(int j = 0; j < test.get(i).size(); j++) {
System.out.println(test.get(i).get(j));
}
}
}
}

Saving a 2-dimensional Sting Array in a .txt file and load from it

I want to save a 2-dimensional String Array in a .txt file and load it from it in my app. The Array should be editable and expandable in the app. I am not really experienced with BufferedWriter, BufferedReader, FileInputStream and FileOutputStream and things like this.
I have problems with this code: The BufferedWriter and BufferedReader throws a NullPointerException and I don't know why. Or does everyone know a possibillity to do this with FileInputStream and FileoutputStream?
public String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");
public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
public static String[][] Load(File file)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;
String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself
String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}
I think that the problem would be with the scope of variables in multiple braces you've used. try this code:
public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}
try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

Java - Problems with returning an integer array

I'm trying to read a .txt file called Heights.txt, which contains a string of numbers, each separated by a ":". The method produces one error that I can't seem to figure out.
It says that "the method must return a result of type int[]", at the very first line of this code.
I don't understand why it says this, as integerHeightDataPoints should be an integer array at that point, and should be able to be returned to a int[] method?
public static int[] readFile(){
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("Path\\Heights.txt"));
}
catch(IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
try {
while((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
int[] integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
}
catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
}
It's because you don't return anything in second IOException case or (as #Exception_al mentioned) when while never triggers.
public static int[] readFile() {
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("/tmp/file1"));
} catch (IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
int[] integerHeightDataPoints = new int[0];
try {
while ((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
return integerHeightDataPoints;
}

Is it possible to read data from file and store it into 2d Array,when we don't know the number of line in the file,in java

I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.

Categories