I'm trying to write a method to take a multiline tab-delimited file and return the contents of that file as an arraylist of String arrays (each line is a String[], and each such String[] is an element of an arraylist). My problem is, I can't tell if the output is correct or not. I've printed each arraylist element and String[] element as they are saved to the arraylist, and those printings look correct. But after the arraylist is returned and I print the String[] in it, they appear to only have the contents of the very last line of the file. I'm suspecting it might be something about FileReader or BufferedReader that I don't know. Anyhoo, here's the code:
public class DataParsingTest {
static File AAPLDailyFile = new File("./textFilesForMethodTests/dataParsingPractice2.tsv");
public static void main(String[] args) throws FileNotFoundException, IOException {
ArrayList<String[]> stringArrayList = fileToStringArray(AAPLDailyFile);
System.out.println("stringArray.size() = " + stringArrayList.size());
System.out.println(stringArrayList.get(0)[0]);
for (int i = 0; i < stringArrayList.size(); i++) {
for (int j = 0; j < stringArrayList.get(i).length; j++) {
System.out.println("index of arraylist is " + i + " and element at index " + j + " of that array is " + stringArrayList.get(i)[j]);
}
}
}
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> arrayListOfStringArrays = new ArrayList<String[]>();
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int nextChar = 0;
int noOfTokens = 1; // because the first token doesn't have a tab or newline before it
int startIndex = 0, endIndex = 0, tokenIndex = 0;
String toRead = "";
toRead = bufferedReader.readLine();
for (int i = 0; i < toRead.length(); i++) {
if (toRead.charAt(i) == '\t') {
noOfTokens++;
}
}
System.out.println("noOfTokens = " + noOfTokens);
bufferedReader.close();
fileReader.close();
String[] productString = new String[noOfTokens];
startIndex = 0;
endIndex = 0;
tokenIndex = 0;
FileReader fileReader2 = new FileReader(file);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
tokenIndex = 0;
int count = 1;
while ((toRead = bufferedReader2.readLine()) != null) {
System.out.println("toRead = " + toRead);
startIndex = -1; // [L - so that the first time an array element is assigned, it's upped to 0]
endIndex = 0;
tokenIndex = 0;
while (true) {
endIndex = toRead.indexOf("\t", startIndex + 1);
if (endIndex == -1) {
productString[tokenIndex] = toRead.substring(startIndex + 1);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
tokenIndex++;
count++;
arrayListOfStringArrays.add(productString);
System.out.println("just added an array to the list. the first element is " + productString[0]);
break;
}
productString[tokenIndex] = toRead.substring(startIndex + 1, endIndex);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
startIndex = endIndex;
tokenIndex++;
count++;
}
}
fileReader2.close();
bufferedReader2.close();
return arrayListOfStringArrays;
}
}
The input file is:
1 2
3 4
5 6
The output is:
noOfTokens = 2
toRead = 1 2
tokenIndex = 0
productString[0] = 1
tokenIndex = 1
productString[1] = 2
just added an array to the list. the first element is 1
toRead = 3 4
tokenIndex = 0
productString[0] = 3
tokenIndex = 1
productString[1] = 4
just added an array to the list. the first element is 3
toRead = 5 6
tokenIndex = 0
productString[0] = 5
tokenIndex = 1
productString[1] = 6
just added an array to the list. the first element is 5
stringArray.size() = 3
5 // from here on up, it looks like the method works correctly
index of arraylist is 0 and element at index 0 of that array is 5
index of arraylist is 0 and element at index 1 of that array is 6
index of arraylist is 1 and element at index 0 of that array is 5
index of arraylist is 1 and element at index 1 of that array is 6
index of arraylist is 2 and element at index 0 of that array is 5
index of arraylist is 2 and element at index 1 of that array is 6 //these 6 lines only reflect the last line of the input file.
Thanks a mil!
You're only creating a single string array, and reusing that for all lines. So your ArrayList just contains multiple references to the same object. You need to understand that when you call arrayListOfStringArrays.add(productString); that's not adding a copy of the array to the ArrayList - it's just adding a reference. (The value of productString is just a reference, not the array itself.)
Just move this:
String[] productString = new String[noOfTokens];
into the while loop, and all should be well. (In this respect, anyway. You should also be closing your file handles in finally blocks.)
That looks like too much code for me to process. Try this altered fileToStringArray method.
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> returnVal = new ArrayList<String[]>();
// Scanner is a nifty utility for reading Files
Scanner fIn = new Scanner(file);
// keep reading while the Scanner has lines to process
while (fIn.hasNextLine()) {
// take the next line of the file, and split it up by each tab
// and add that String[] to the list
returnVal.add(fIn.nextLine().split("\t", -1));
}
return returnVal;
}
Related
I am creating a program that is reading a file of names and ages then printing them out in ascending order. I am parsing through the file to figure out the number of name age pairs and then making my array that big.
The input file looks like this:
(23, Matt)(2000, jack)(50, Sal)(47, Mark)(23, Will)(83200, Andrew)(23, Lee)(47, Andy)(47, Sam)(150, Dayton)
When I am running my code I get the output of (0,null) and I am not sure why. I have been trying to fix it for a while and am lost. If anyone can help that would be great My code is below.
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
output example
File to read from:
file.txt
(0,null)
Process finished with exit code 0
What your code does is to Scan the file twice.
In the first loop you do
String data1 = inputFile.nextLine();
Code reads first line and then scanner goes to the next (second) line.
Later you do again inputFile.nextLine(); The second line is empty and the code never goes into the second loop and content is never read.
If you can use Lists, you should create two array lists and add ages and names into the arraylists in the first scan, so you scan the file once. When done, you could get the Array out of the arraylist.
If you should only use arrays and you want a simple update, just add another Scanner before the second loop:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line
i am trying to solve a maze using either BFS or DFS, the maze numbers are given in a text file so i have to read line by line then convert each string to integers and store each line in an array of size 2 then i store this array in an arraylist.
secondly in the findRow method i try to search each element in the array and print out the numbers related to it either left or right.
but my main goal is to use any search method print out the fastest way to the end of the maze. the text file is in this format 0 and 1 is the starting and ending node.
11 3
2 3
0 3
1 4
5 4
5 7
6 7
7 8
8 9
9 10
0 5
================
my code
public class Mazes {
ArrayList<int[]> collections = new ArrayList();
public String toString() {
String result = "";
for (int i = 0; i < collections.size(); i++) {
result += collections.get(i)[0];
result += " ";
result += collections.get(i)[1];
result += "\n";
}
return result;
}
public void getMazes() throws Exception{
try{
FileInputStream fstream = new FileInputStream("C:\\csd3939\\maze1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine()) != null){
String[] splitStringArray = strLine.split(" ");
int[] intElementArray = new int[2];
for(int i=0; i<splitStringArray.length; i++){
intElementArray[i] = Integer.parseInt(splitStringArray[i]); }
collections.add(intElementArray);
}
System.out.print("\n");
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public ArrayList<Integer> findRowConnection(int rowID){
ArrayList<Integer> connectRow = new ArrayList();
for(int i=0; i<collections.size(); i++){
int[] searching = collections.get(i);
if(rowID == searching[0]){
connectRow.add(searching[1]);
}
if(rowID == searching[1]){
connectRow.add(searching[0]);
}
}
return connectRow;
}
}
===========
main method
===========
public class MazeMain {
public static void main(String[] args)throws Exception{
Mazes mainmaze = new Mazes();
mainmaze.getMazes();
System.out.println(mainmaze);
ArrayList<Integer> searchResult = mainmaze.findRowConnection(0);
System.out.println("Connected Rows are :");
for(int i=0; i<searchResult.size(); i++){
System.out.println(searchResult.get(i));
}
}
}
I am trying to read a simple .CSV file and create a 2D array of Strings. Here is the array:
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
4,4,4,4,4,4
My code is supposed to find six columns and four rows, but it stops after the third column and moves on to the next row and I cannot figure out why this is happening.
In addition to this, it returns an out of bounds exception even though it quits early.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
Here is the code and it is followed by the output.
public String[][] ascToStringArray(String ascFileIn) {
String directory ="c:\\data\\"; // "\" is an illegal character
String[][] numbers= new String[4][6]; // 4 rows 6 columns
try{
BufferedReader Br = new BufferedReader(new FileReader(directory + ascFileIn));
String line;
int row = 0;
int col = 0;
//read each line of text file
while((line = Br.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line,",");
//Populating Columns
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.println(row + " " + col + " = " + st.nextToken());
col++;
}
row++;
}
//close the file
Br.close();
return numbers;
}
catch(IOException exc) {
System.out.println("Error reading file.");
return numbers;
}
}
Here is the output:
0 0 = 1
0 1 = 1
0 2 = 1
1 3 = 2
1 4 = 2
1 5 = 2
If anyone can figure out why it is quitting early and throwing me an out of bounds error no matter how large I make the array I would really appreciate it.
You are using nextToken twice.
numbers[row][col] = st.nextToken();<-1---
System.out.println(row + " " + col + " = " + st.nextToken());<--2--Skips element
But using only one value so in one row only three element of line will be added.
Reason of Exception
You are not resetting the col=0 after the execution of inner while loop which leads to ArrayIndexOutOfBound for col=6 as col size in array is 6 means 0 to 5 so will throw exception when col=6.
Firstly the system.out.println inside the inner while loop consumes a token.. Second on entring the inner while loop you should reset the cols files. to zero.
public String[][] ascToStringArray(String ascFileIn) {
String directory = "c:\\data\\"; // "\" is an illegal character
String[][] numbers = new String[4][6]; // 4 rows 6 columns
try {
BufferedReader Br = new BufferedReader(new FileReader(directory + ascFileIn));
String line;
int row = 0;
int col = 0;
// read each line of text file
while ((line = Br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",");
col = 0;
// Populating Columns
while (st.hasMoreTokens()) {
// get next token and store it in the array
numbers[row][col] = st.nextToken();
col++;
}
row++;
}
// close the file
Br.close();
return numbers;
} catch (IOException exc) {
System.out.println("Error reading file.");
return numbers;
}
}
It's because you are calling st.nextToken() twice, swallowing an extra token in your System.out.println.
Instead, first save it into a String:
String token = st.nextToken();
then you can use the same String in your print and for the array.
http://msdn.microsoft.com/fr-fr/library/aa989865(v=vs.80).aspx
StringTokenizer.nextToken () : Gets the next token in the string
during parsing.
numbers[row][col] = st.nextToken();
System.out.println(row + " " + col + " = " + st.nextToken());
You go through your tokens without using them !
Any ideas what I am missing here? I am reading from a file array. The values in the text file don't get stored and there is no output. All I get is "names and totals" but no values.
I don't know.
private int[] totals;
private String[] names;
private String[] list;
private int count;
public void readData() throws IOException {
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
//create the arrays
totals = new int[count];
names = new String[count];
list = new String[count];
//read in each pair of values
String quantityString = input.readLine();
for (int i = 0; i < count; i++) {
names[i] = input.readLine();
list[i] = input.readLine();
quantityString = input.readLine();
totals[i] = Integer.parseInt(quantityString);
}
}
public void display() {
System.out.println("names totals")
for (int i = 0; i < count; i++)
System.out.println(list[i] + " \t " + names[i] + " \t" + totals[i]);
}
//called to compute and print the result
public void printResults() {
//find the best teacher
int maxIndex = 0;
int maxValue = 0;
//for each record stores
for (int i = 0; i < count; i++) {
//if we have a new MAX value so far, update variables
if (maxValue < totals[i]) {
maxValue = totals[i];
maxIndex = i;
}
}
}
You never give the variable count a value, so it initialized to 0 by Java. This means that your arrays are of size 0 also.
So since count is zero, you never read anything from the file, which is why nothing is stored in your arrays and also why nothing is printed out.
Example: Reading a File line-by-line
// create temporary variable to hold what is being read from the file
String line = "";
// when you don't know how many things you have to read in use a List
// which will dynamically grow in size for you
List<String> names = new ArrayList<String>();
List<Integer> values = new ArrayList<Integer>();
// create a Reader, to read from a file
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
// read a full line, this means if you line is 'Smith 36'
// you read both of these values together
while((line = input.readLine()) != null)
{
// break 'Smith 36' into an array ['Smith', '36']
String[] nameAndValue = line.split("\\s+");
names.add(nameAndValue[0]); // names.add('Smith')
values.add(Integer.parseInt(nameAndValue[1]); // values.add(36);
}
In my application I need to read a specific column of tab separated csv file using jsp. But I can read the data of full row not a specific column.
I need help this regard. Please help me
Thanks
mycode:
<%# page import="java.io.*"%>
<html>
<body>
<%
String fName = "c:\\csv\\myfile.csv";
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
%>
<table>
<%
while ((thisLine = myInput.readLine()) != null)
{
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
if(i!=0)
{
out.print(" " +strar[j]+ " ");
}
else
{
out.print(" <b>" +strar[j]+ "</b> ");
}
}
out.println("<br>");
i++;
}
%>
</table>
</body>
</html>
I don't think you can read specific column.Better to read entire row using CSVParser or you can read CSV line by line and split it and get String array then you can get specific column but yes you need to read whole row gain.
Try it.
String fName = "C:\\Amit\\abc.csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
while ((thisLine = myInput.readLine()) != null) {
String strar[] = thisLine.split(",");
System.out.println(strar[3]);
// Here column 2
}
}
By this way you can read specific column.
I had a similar problem in Objective C the other day, but this is how I solved it.
This method assumes you know the column number of the data you want. (I.E. if you want column 1 of 6)
Read all the rows into strings and append them into one.
Data sample: (columns 1 to 6)
1,2,3,4,5,6
13,45,63,29,10,8
11,62,5,20,13,2
String 1 = 1,2,3,4,5,6
String 2 = 13,45,63,29,10,8
String 3 = 11,62,5,20,13,2
Then you should get this:
String combined = 1,2,3,4,5,6,13,45,63,29,10,8,11,62,5,20,13,2 //add in the missing "," when you concatenate strings
Next you need to split the string into an array of all values.
Use code somewhat like this: (written off the top of my head so may be off.)
String[] values = combined.split(",");
Now you should have something like this:
Values = `"1", "2", "3", ... etc`
The last step is to loop through the entire array and modulo for whatever column you need:
//Remember that java numbers arrays starting with 0.
//The key here is that all remainder 0 items fall into the first column. All remainder 1 items fall into the second column. And so on.
for(int i = 0; i < values.length(); i++)
{
//Column1 - Column6 -> array lists of size values.length/number of columns
//In this case they need to be size values.length/6
if(i % 6 == 0)
column1.add(values[i]);
else if(i % 6 == 1)
column2.add(values[i]);
else if(i % 6 == 2)
column3.add(values[i]);
else if(i % 6 == 3)
column4.add(values[i]);
else if(i % 6 == 4)
column5.add(values[i]);
else if(i % 6 == 5)
column6.add(values[i]);
}
~~~~~~~~~~~~~~~~
Edit:
You added code to your question. Above I was saving them into memory. You just loop through and print them out. In your while loop, split each line separately into an array and then either hardcode the column number or modulo the length of the array as the index.
public class ParseCSVs {
public static void main(String[] args) {
try {
// csv file containing data
String strFile = "./input//SIMNumbers.csv";
String line = "";
System.out.println("Enter line number to configure");
Scanner sc = new Scanner(System.in);
int lineNumber = sc.nextInt();
BufferedReader br = new BufferedReader(new FileReader(strFile));
if ((line = br.readLine()) != null) {
String cvsSplitBy = ",";
String blankCell = null;
// use comma as separator
String[] cols = line.split(cvsSplitBy);
for (int i = 0; i < cols.length; i++)
System.out.println("Coulmns = " + cols[i]);
// System.exit(0);
} else
System.out.println("No data found in csv");
} catch (IOException e) {
e.printStackTrace();
}
}