Java - Reading from csv file getting null value - java

I am getting a null value when im reading from my teachers. csv file. Column 1 which is att[0] works but att[1] returns 3 null values.
My csv looks like this:
1, Mr Murphy
2, Mr Davis
3, Ms Simpson
Each on separate lines ie line 1 -> 1, Mr Murphy etc
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV
{
public static void main(String[] args)
{
//Input file which needs to be parsed
String readTeachers = "teacher.csv";
BufferedReader fileReader = null;
//Delimiter used in CSV file
final String DELIMITER = ",";
try
{
String line = "";
//String line = inFile.readLine();
//Create the file reader
fileReader = new BufferedReader(new FileReader(readTeachers));
int count=0;
String[] att = new String[10];
//Read the file line by line
while ((line = fileReader.readLine()) != null)
{
//Get all tokens available in line
String[] tokens = line.split(DELIMITER);
int i=0;
count++;
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break;
}
}
//System.out.println(count);
//System.out.println(att[1]);
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Your issue here is that you have a break statement inside the for loop that exits the loop at the end of the first iteration. Therefore, you are only putting a value in the first index of your array. Take out that statement and it should be fine.
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break; // <---- ***take this out***
}

Related

How to parse a simple text file in java

I would need to parse a text file with below format and extract only the required values from the text file. the content of the text file is
4564444 FALSE / TRUE 0 name k0LiuME5Q3
4342222 TRUE / TRUE 0 id ab4454jj
i need to get the values after name and id. what is the best way. I used Scanner Class in java but could not get the values. tried with below code.
Scanner scanner = new Scanner(new File("test.txt"));
while(scanner.hasNext()){
String[] tokens = scanner.nextLine().split(" ");
String last = tokens[tokens.length - 1];
System.out.println(last);
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Read_Text_File {
public static void main(String[] args) {
System.out.println(getValues());
}
public static ArrayList<String> getValues() {
FileInputStream stream = null;
try {
stream = new FileInputStream("src/resources/java_txt_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String strLine;
ArrayList<String> lines = new ArrayList<String>();
try {
while ((strLine = reader.readLine()) != null) {
String lastWord = strLine.substring(strLine.lastIndexOf(" ")+1);
lines.add(lastWord);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}
Output:
[k0LiuME5Q3, ab4454jj]
You need to split by space, not semicolon:
String[] tokens = scanner.nextLine().split(" ");
read the data line by line, on each line use String.split("\s*") to get the parts without the whitespace into an array with 7 elements. the last one of these elements is what you are looking for.

Reading Line of String in Text File is Not Consistent

Hi StackOverFlow People,
I have this issue in my development of System, where I have 4451 lines of record in a text file, and I am retrieving it using BufferedReader and split every line by pipe ( | ). I'm using Quartz also to run this reading of file every day. when I test it, I set the quartz job every minute so I can test It if it actually reading the file in every minute. It reads all of the line in the text file by checking it using this.
BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream));
String line = null;
int counter = 0;
while((line = reader.readLine()) != null){
counter++;
}
System.out.println(counter);
But when I split the String, The result of retrieving 4451 records is inconsistent. Sometimes, It only retrieves 1000+ to 2000+ records, and Sometime it retrieves 4451, but not consistently. This is my code.
try {
BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream));
String line = null;
int counter = 0;
String[] splitLine = null;
while((line = reader.readLine()) != null){
splitLine = line.split("\\|"); // Splitting the line using '|' Delimiter
for(String temp : splitLine) {
System.out.println(temp);
}
counter++;
}
System.out.println(counter);
} catch (IOException e) {
e.printStackTrace();
}
Is the splitting of String and Iterating of the readfile at the same time could be the cause?
EDIT:
There's no Exception Occured in the Situation. It Only print the length of by using the counter variable.
My Expected Output is I want to Retrieve all the records per line in the text file and split the string per line by pipe. counter is the count of lines retrieved.
I didn't find any error in your code but the code that I have written is working perfectly fine. Here is the code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class Test {
public static void main(String[] args) {
FileReader inputStream = null;
BufferedReader reader = null;
try {
inputStream = new FileReader("Input.txt");
reader = new BufferedReader(inputStream);
String line = null;
int counter = 0;
String[] splitLine = null;
while ((line = reader.readLine()) != null) {
splitLine = line.split("\\|");
for (String temp : splitLine) {
System.out.println(temp);
}
counter++;
}
System.out.println(counter);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Shouldn't pipe delimiter be just "|" instead of "\\|"?
Try Changing your code to:
splitLine = line.split("|"); // Splitting the line using '|' Delimiter

JAVA: How to sort strings read from file and output to console in alphabetical order?

I'm looking to sort the contacts read from a file in alphabetical order by last name to the console? How would I go about doing so? The contacts are already written to file starting with the last name, I just want to read them back into the application in alphabetical order when a user wants to view the contacts in the console.
// Read from file, print to console. by XXXXX
// ----------------------------------------------------------
int counter = 0;
String line = null;
// Location of file to read
File file = new File("contactlist.csv");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
counter++;
}
scanner.close();
} catch (FileNotFoundException e) {
}
System.out.println("\n" + counter + " contacts in records.");
}
break;
// ----------------------------------------------------------
// End read file to console. by XXXX
Before printing, add each line to a sorted set, as a TreeSet:
Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lines.add(line);
counter++;
}
for (String fileLine : lines) {
System.out.println(fileLine);
}
package main.java.com.example;
import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
public class ReadFromCSV {
public static void main(String[] args) {
try {
final ClassLoader loader = ReadFromCSV.class.getClassLoader();
URL url = loader.getResource("csv/contacts.csv");
if (null != url) {
File f = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(f));
Set<String> set = new TreeSet<String>();
String str;
while ((str = br.readLine()) != null) {
set.add(str);
}
for (String key : set) {
System.out.println(key);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read names from the file, put them in an object of class SortedSet.

Parsing Data from CSV to Array in Java

I'm trying to import a CSV file into an array that I can use within a Java program. The CSV file has successfully imported itself and the output appears on Terminal but it throws the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at CompareCSV.main(CompareCSV.java:19)
at the end. In addition, when I try to call up elements in the array, it also shows the same error. My code is below:
import java.io.*;
import java.util.*;
public class CompareCSV {
public static void main(String[] args) {
String fileName = "sampledata1.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are much better off using a proper CSV parser than hacking a faulty one up yourself: http://opencsv.sourceforge.net/
CSV is not the simple format one might be let to think (yes, a line can contain a , that does not separate two pieces of data).
This is the answer for above Question
public class Readline {
/**
* #param args
*/
public static void main(String[] args) {
String fileName = "C:/Users/karthikrao/Desktop/cvsFile.csv";
ArrayList<Integer> margins = new ArrayList<Integer>();
BufferedReader br;
String line, token;
int i;
try {
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
if (margins.size() <= i) {
margins.add((Integer) token.length());
} else {
margins.set(
i,
Math.max(margins.get(i),
(Integer) token.length()));
}
i++;
}
}
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
System.out.print(token);
for (int j = 0; j < margins.get(i) - token.length(); j++) {
System.out.print(" ");
}
System.out.print("|");
i++;
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I suggest you not re-inventing wheel when there are so many great libraries out there. Try the uniVocity-parsers with the following code snippt as reference:
public static void main(String[] args) throws FileNotFoundException {
/**
* ---------------------------------------
* Read CSV rows into 2-dimensional array
* ---------------------------------------
*/
// 1st, creates a CSV parser with the configs
CsvParser parser = new CsvParser(new CsvParserSettings());
// 2nd, parses all rows from the CSV file into a 2-dimensional array
List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));
// 3rd, process the 2-dimensional array with business logic
// ......
}
As you can see, only 2 lines required to finish the task of parsing csv data into array. Additionally, the library provides full list of features in parsing CSV data with excellent performance.
Looks like your assumption, that a line in the file always has three columns isn't true for all lines. Replace the for loop statement with the following line to eliminate the exception and see, why it happend:
for (int x=0; x<result.length; x++)

Method to find string inside of the text file. Then getting the following lines up to a certain limit

So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters

Categories