Read and parse CSV file in java - java

I have two csv files.
CSV File1=csvFrom, //It has two columns, column1=Email(only 5 emails), Column2=Password
CSV File2=csvSendTo //It has only one column = Email. (Thousands of emails).
I am trying to read csvFrom file, I want first email id and its password from first file. Then 20 emails from second csvSendTo file. Want to send emails from first email id and password to these 20 emails. I am able to send email manually with one email id. But when I tried to read it from csv file, its giving me a NullPointerException. Below is my code:I am just pasting the part over here which is giving me an error. Can anyone guide me here? This for loop is wrong here but I am bit confused,so not able to replace with accurate loop.
BufferedReader br1=null;
BufferedReader br2=null;
String line1="",line2="";
String csvSplitBy=",";
String strMailFrom="",strPassword="";
int countCSVFrom=0,countCSVSendTo=0;
System.out.println("strCSVFrom=" + strCSVFrom + ", strcsvSendTo=" + strCSVSendTo);
try{
br1=new BufferedReader(new FileReader(strCSVFrom));
br2=new BufferedReader(new FileReader(strCSVSendTo));
String[] strarrFromEmail;
while((line1=br1.readLine())!=null){
countCSVFrom+=1;
strarrFromEmail=line1.split(csvSplitBy);
// for(int i=countCSVFrom-1;i<=countCSVFrom;i++){
// strMailFrom=strarrFromEmail[i];
// strPassword=strarrFromEmail[i+1]; //While here its ArrayIndexOutOfBounds Exception
// }
//what is the correct thing to write it over here instead of for loop?
}
System.out.println("countcsvfrom="+countCSVFrom + ", line1=" + line1.toString()); //Giving me an error of NullPointerException over here.
System.out.println("strFrom="+strMailFrom + ", strPassword="+strPassword);
while((line2=br2.readLine())!=null){
countCSVSendTo+=1;
}
System.out.println("countcsvsendto="+countCSVSendTo);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}

The second System.out.println, just after the closing brace of the first while loop, gives the NPE. It uses line1, which the terminating condition of said while loop guarantees will be null at that point.

You could write:
//your code here and try catch block below
try {
List<String[]> csvLines = new ArrayList<String[]>();
Files.lines(Paths.get(strCSVFrom)).map(e -> e.split(csvSplitBy)).forEach(csvLines.add(e));
} catch (Exception) {
//exception handling
}

Related

How do I update the contents of a file before reading it?

I am coding a program that requires me to be able to write the personal details of people to an excel file. I must be able to then read the contents of this file and present them in a combo box. However currently if I run the program and enter the details of a person, then use the combo box to select one of these people, anybody entered on the current run-through of the program will not be shown in the combo box. If I close the program and run it again, however, they will then appear. How can I fix this?
String csvFile = "Clients.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String fullName = null;
try {
File file = new File("Clients.csv");
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
fullName = data[0]+" "+data[1];
comboBox_1.addItem(fullName);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//FILE READING END
comboBox_1.setBounds(130, 25, 584, 20);
existingClients.add(comboBox_1);
When you run your program, your BufferedReader is fed with the csv file with current data in it. In run time your program doesn't know whether you entered new entries in your csv file.
You should write a block of code which updates the csv file when you hit the "Add Person" button(or whatever you call it in your program), then triggers a new BufferedReader.
Edit:
I don't know your program is a gui or a console application, but I will try to explain as if we are talking about a gui.
Step - 1 --> When the user fills the details of a new person in a textarea in your program, or when s/he hits the "Add Person" button, you should store the details of this person.
Step - 2 -->Then you must create a writer instance. This instance must append new data to your csv file;
BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile));
writer.write("\n" + newPersonDataasString + "\n");
Step - 3 -->Finally, you must read your file again using a new BufferedReader fed with your csv file.
as exe-cute-table mentioned, wrapping these steps into custom methods like readFile(), writeFile() is a good solution for maintaining purposes.
Let me now if I misdirected you.
Each time you write in your file, you have to open it again (with the BufferedReader as you did) too see the changes. The BufferedReader, once created, won't store the new changes of your CSV file.
So the best way is to have two functions:
readFile(filename) which will read the file using the BufferedReader (which is created, used and closed)
writeFile(filename, contentToWrite) which will write into the file using the BufferedWriter (which is also created, used and closed)
Each time you add a person, call writeFile("your.csv", your_data).
Each time you want to display the datas from your csv (e.g listing all people stored in), call readFile("your.csv")

How to print multiple exceptions in an input file to an errors file?

I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}

Blank lines when reading CSV file in Java

I've been working on this app in Android for a while now and suddenly encountered the following issue even though it has not been a problem many times before.
I am reading a CSV file in Java, but when I print a log of each line of that CSV file, there appears to be a blank line even though there is not one in the actual CSV file.
This is how I'm reading the file:
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(getActivity().getAssets().open("My_file.csv"));
Scanner inputStream = new Scanner(inputStreamReader);
inputStream.nextLine(); // Ignores the first line
while (inputStream.hasNext()) {
String data = inputStream.nextLine(); // Gets a whole line
String[] line = data.split(","); // Splits the line up into a string array
array.add(line[1]);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
When I run it, I get an ArrayIndexOutOfBoundsException and after putting in a log message before array.add(line[1]) which printed the line, I found that there was a blank line in my CSV file (and there wasn't when I checked it).
Any ideas?
First of All:
array.add(line[1]) is going to throw an ArrayIndexOutOfBoundsException every time you have a line without a , ... Might be a good idea to check for that before trying to read it. i.e. if(line.length > 1) { array.add(line[1]);}
Just doing this will fix multiple errors for you.

Writing to a text file within a loop - JAVA

I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm

Java: No input from Process object until the program closes

I'm trying to get input from the console of a .exe process started by a Java script. Nothing appears in the console window, and nothing is read by the program until the process is terminated.
blServ = new ProcessBuilder(blPath + "Blockland.exe", "ptlaaxobimwroe", "-dedicated", "-port " + port, "-profilepath " + blPath.substring(0, blPath.length() - 1)).start();
System.out.println("Attempting to start server...\n" + blPath);
consoleIn = new BufferedReader(new InputStreamReader(blServ.getInputStream()));
'blServ' is a Process object. And yes, the program is starting successfully.
public void blStreamConsole() //called once every 500 milliseconds
{
String lineStr = "";
String line = "";
int lines = 0;
try
{
if (consoleIn != null)
{
while ((line = consoleIn.readLine()) != null)
{
//if (!line.equals("%"));
//{
lineStr += line + wordSym;
lines++;
//}
}
}
}
catch (IOException e)
{
netOut.println("notify" + wordSym + "ERROR: An I/O exception occured when trying to get data from the remote console. Some lines may not be displayed.");
}
if (!lineStr.equals("") && !(lineStr == null))
netOut.println("streamconsole" + wordSym + lines + wordSym + lineStr);
}
Basically, this method sees if there is more input waiting in the consoleIn object, and if there is, it appends every line it has to another string, and that other string is sent to a client. Unfortunately, it is all sent in one big chunk right when Blockland.exe is closed. Sorry about the indenting issues. The Stackoverflow editor re-arranged all of the code.
It seems to me that there are two possibilities here:
readLine blocks, waiting for input (and doesn't return null as you expect). You may be able to fix it by not using BufferedReader and instead using the InputStream
The output stream doesn't flush until all the input has been written. Try putting a flush there:
Also note that if lineStr is null, you'll get a NullPointerException as your code currently is (you need to swap your conditions), but it can't even be null.
if (!lineStr.isEmpty())
{
netOut.println("streamconsole" + wordSym + lines + wordSym + lineStr);
netOut.flush();
}
while ((line = consoleIn.readLine()) != null){
lineStr += line + wordSym;
lines++;
}
The problem with this piece of code is that it will keep running until the program exits. It will append every single line to lineStr until the program exits (when console.readLine() is null). The whole lineStr is then printed afterwards, containing the whole console.
If you want to continuously print the output, you will need to print it immediatly:
while ((line = consoleIn.readLine()) != null){
netOut.println(line);
}
You can run this in one separate thread, and it will keep outputting the console to the output stream until the program exits.

Categories