I have a txt file like this:
5
1
3
6
9
I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?)
the file only contain ints.
I tried read them into a string
and use this to convert
static public int[] strToA(String str)
{
int len = str.length();
int[] array = new int[len];
for (int i = 0; i < len; i++)
{
array[i] = Integer.parseInt(str.substring(i,i+1));
}
return array;
}
Scanner can help you read your file, and you can use a List or something else to store the info.
After that, you can use this List to convert your Array.
public static Integer[] read2array(String filePath) throws IOException {
List<Integer> result = new ArrayList<Integer>();
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
String line = null;
while(null != (line = randomAccessFile.readLine())) {
result.add(new Integer(line));
}
randomAccessFile.close();
return result.toArray(new Integer[result.size()]);
}
Code would be something like this. This is untested code and may have Syntax errors.
Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
intArr = new int[10]; // bad code could fail if file has more than 10
int i = 0;
while ((line = reader.readLine()) != null) {
intArr[i++] = Integer.parseInt(line); // parse String to int
}
} catch (IOException x) {
System.err.println(x);
}
To use List instead of array change line
intArr = new int[10];
to
List intArr = new ArrayList();
Code would be something like
List intArr = new ArrayList();
while ((line = reader.readLine()) != null) {
intArr.add(Integer.parseInt(line)); // parse String to int
}
Related
I'm being completely beaten up by types in Java.
I have coordinates in a txt file, which ultimately I want to format into an array of these co-ordinates, with each array item being a double.
Each line of my txt file looks like so:
13.716 , 6.576600074768066
Currently, I'm trying to split this line into an array of two Strings, which I will then try and parse into doubles, but I keep getting the error in the title. Where am I going wrong?
Any other better approaches on converting my Arraylist of Strings to a formatted list of double coordinates would be great, like so
[[0,1], [0,2], 0,4]
Code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
The split(",") method return array of string string[] and you can't set string by array of string.
Crate point class with let lan double variabels and then create array of this point and them fill them with data from reading each line:
class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}
And then use this class in your code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);
double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
you can update your while loop like this
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}
I have the following file
3
2,3,4,5
6,7,8
9,10
and I am trying to convert it to pass it as jagged array of double. By that I mean, I am trying to store this as
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
I have been able to get the values read from the file but I am stuck on 2 things.
How can I convert the values into double array?
How can I store the last elements into a new array?
I am facing the error because my array contains comma separated values but how can I get the individual values to convert to double? I am still new to Java so I am not aware of all the inbuilt methods.
here is what I have so far
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It looks like the first line gives you the number of lines in the rest of the file. You can leverage it to make the arrays upfront, like this:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
Similarly, you can use String.split method to find out how many entries is to be added to the jagged array. This way the code becomes much shorter, because you can pre-allocate all your arrays.
Demo.
I have this code here, that reads numbers from a file and stores them in a String array.
public static void main(String [] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt"));
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
for(String str : values){
System.out.println(str);
}
}
System.out.println("");
br.close();
}
But if I wanted to store the values from the String array in a int array, how should I do?
The file that I'm reading looks something like this.
23,64,73,26
75,34,21,43
After String[] values = line.split(",");...
// new int[] with "values"'s length
int[] intValues = new int[values.length];
// looping over String values
for (int i = 0; i < values.length; i++) {
// trying to parse String value as int
try {
// worked, assigning to respective int[] array position
intValues[i] = Integer.parseInt(values[i]);
}
// didn't work, moving over next String value
// at that position int will have default value 0
catch (NumberFormatException nfe) {
continue;
}
}
... and to test:
System.out.println(Arrays.toString(intValues));
Use parseInt(String) to convert every string to int
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
int[] intvalues = new int[values.length];
for (int i = 0; i < values.length; i++) {
intvalues[i] = Integer.parseInt(values[i]);
}
You would need to parse your string into an int:
while((line = br.readLine()) != null){
String[] values = line.split(",");
int[] values2=new int[values.length];
for(int i=0; i<values.length; i++){
try {
values2[i]= Integer.parseInt(values[i]);
//in case it's not an int, you need to try catching a potential exception
}catch (NumberFormatException e) {
continue;
}
}
}
I want to read a text file and store it as string multidimensional array in java.
The input will be like this
11 12 13
12 11 16
33 45 6
I want to store this in
String[][] as={{"11","12","13"},
{"12","11","16"},
{"33","45"}};
My code
String file="e:\\s.txt";
try
{
int counterCol=0,counterRow=0;
String[][] d=null;
BufferedReader bw=new BufferedReader(new FileReader(file));
String str=bw.readLine();
String[] words=str.split(",");
System.out.println(words.length+"Counterrow");
counterCol=words.length; //get total words split by comma : column
while(bw.readLine()!=null)
{
counterRow++;
// to get the total words as it gives total row count
}
String[][] d=new String[counterRow][counterCol];
for(int x=0;x<counterRow;x++)
{
for(int y=0;y<counterCol;y++)
{
d[x][y]=bw.readLine();
//storing in array. But here gives me the exception
}
}
But I cannot store it in array as I getting null pointer exception. How to over come this problem
Quite a few things wrong here:
Array not initialized
You are not looping over the file lines using the BufferedReader
You are splitting by comma instead of space as specified in your sample data
Using Java Collections will help you here. Specifically ArrayList.
Give something like this a go:
String file="e:\\s.txt";
try {
int counterRow = 0;
String[][] d = new String[1][1];
BufferedReader bw = new BufferedReader(new FileReader(file));
List<List<String>> stringListList = new ArrayList<List<String>>();
String currentLine;
while ((currentLine = bw.readLine()) != null) {
if (currentLine != null) {
String[] words = currentLine.split(" ");
stringListList.add(Arrays.asList(words));
}
}
// Now convert stringListList into your array if needed
d = Arrays.copyOf(d, stringListList.size());
for (List<String> stringList : stringListList) {
String[] newArray = new String[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
newArray[i] = stringList.get(i);
}
d[counterRow] = newArray;
counterRow ++;
}
} catch (Exception e) {
// Handle exception
}
You get NullPointer because your array 'd' is null:
String[][] d=null;
Initialize it and it should be work:
String[][] d= new String [counterCol][counterRow];
I am getting null-exception throw error in the following code. What can be the reason for it?
public static String[] CreateVocab(BufferedReader buffR) throws IOException{
String[] arr = null;
int i = 0;
arr[i]= null;
String line = new String();
while((line = buffR.readLine()) != null){
arr[i] = line;
i=i+1;
}
return arr;
}
Compiler is showing Null ponter exception in the code
arr[i]=null.
This is the cause:
String[] arr = null;
int i = 0;
arr[i]= null; // 'arr' is null
As the number of lines being read is unknown suggest using an ArrayList<String> to store the lines read, and the use ArrayList.toArray() to return a String[] (if returning an ArrayList<String> is not acceptable).
Example that returns a List<String>:
public static List<String> CreateVocab(BufferedReader buffR)
throws IOException
{
List<String> arr = new ArrayList<String>();
String line;
while((line = buffR.readLine()) != null){
arr.add(line);
}
return arr;
}
To return an array change return to:
return arr.toArray(new String[]{});
You haven't created the array - and an array won't solve your problem anyway, because it can't resize. We don't know the number of lines in advance.
Use a collection instead:
public static String[] CreateVocab(BufferedReader buffR) throws IOException{
List<String> lines = new ArrayList<String>();
String line = null;
while((line = buffR.readLine()) != null){
lines.add(line);
}
return lines.toArray(new String[]{});
}
String[] arr = null; //here you are setting arr to null
int i = 0;
arr[i]= null; // here you are trying to reference arr