Empty lines not getting printing in reading CSV files in java - java

I have following code in which i m reading a csv file in java,The csv file is as follows
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Following code for reading file in java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVFileReader {
public static void main(String[] args) {
CSVFileReader obj = new CSVFileReader();
obj.run();
}
public void run() {
String csvFile = "Whois.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
if(line.contains("AU") || line.contains("AU"))
{
System.out.println("Country [code= " + country[4]
+ " , name=" + country[5] + "]");
}
else
{
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
With this java code I am reading the lines where i m getting AU in line.it showing correctly two results which is correct,But i want like where ever i m not getting AU string in line.It should print that row as blank.
As we can see in csv file code.That AU is in first and third line,its printing two lines where AU is present.I want the output to be first AU row then second row should be blank and then in third row the required AU values...
How can i print the second empty row as well,right now its printing two rows which contains AU in line

To write an empty line for non AU lines you can write:
String[] country = line.split(cvsSplitBy);
if( line.contains("AU") ) {
System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
} else {
System.out.println("");
}
Though this approach is not an example of a good coding/design (maybe except the case of simplest, single use scripts, where it doesn't really matter).
I'd suggest thinking about separating processing of the CSV results (in the form of method which will take in the CSV file and return the collection of processed lines/results) and printing them out (take in the collection of lines/results and iterate over to print them).
This way you would be able to test in an automated manner that you've processed the results correctly.

Related

How do you allow a user to retrieve values from a list in Java?

I created a list in a FlightBookingSystem Java Class, as you can see below:
public List<Flight> getFlights() {
List<Flight> out = new ArrayList<>(flights.values());
return Collections.unmodifiableList(out);
}
Which I imported from a text file show below:
1::LX2500::Birmingham::Munich::2020-11-25::
2::LX2500::Denmark::London::2021-07-01::
3::LY2380::London::France::2021-06-28::
It's a basic text file which holds the information for each flight
Here is the code I wish to adjust:
public Flight execute(FlightBookingSystem flightBookingSystem, int id)
throws FlightBookingSystemException {
List<Flight> flights = flightBookingSystem.getFlights();
for (Flight Flight : flights) {
if (Flight.getFlightNumber() == flightNumber) {
System.out.println(Flight.getFlightNumber() + " flight(s)");
return flights.get(id);
}
System.out.println(((Flight) flights).getFlightNumber() + " flight(s)");
}
return flights.get(id);
}
How do I change that code so that it allows the user to retrieve one single record from the text file?
Why not to retrieve all and get the one you want by key or id using HashMap ?
If you still want the other option, you can read the text file line by line, and check if it startsWith(...) and the to retrieve this line.
Code example:
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = br.readLine()) != null)
{
// Add here 'if' condition and parse your line
}
}
Your question is a bit confusing. Your title states:
How do you allow a user to retrieve values from a list in Java?
and the very last line of your post states:
How do I change that code so that it allows the user to retrieve
one single record from the text file?
Which is it, from a List or from a text file?
If it's from a List because you already have the mechanism available then is could be something similar to this:
public String getFlightInfo(String flightNumber) {
List<Flight> flights = FlightBookingSystem.getFlights();
for (Flight flite : flights) {
if(flite.getFlightNumber().equalsIgnoreCase(flightNumber)){
return flite.toString();
}
}
JOptionPane.showMessageDialog(null, "<html>Flight number <font color=red><b>"
+ flightNumber + "</b></font> could not be found!</html>", "Flight Not "
+ "Found", JOptionPane.INFORMATION_MESSAGE);
return null;
}
The code above assumes you have an overriden toString() method applied to the Flight class. If you don't then create one.
If it's actually from file then it could be something like this:
public String getFlightInfo(String flightNumber) {
// 'Try With Resouces' to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader("Flights.txt"))) {
String fileLine = "";
while ((fileLine = reader.readLine()) != null) {
fileLine = fileLine.trim();
// If by chance the file line read in is blank then skip it.
if (fileLine.isEmpty()) {
continue;
}
// First, remove the double colons at the end of line (if any).
if (fileLine.endsWith("::")) {
fileLine = fileLine.substring(0, fileLine.lastIndexOf("::")).trim();
}
/* Split each read in file line based on a double colon delimiter.
The "\\s*" within the regex for the split method handles any
cases where the might be one or more whitespaces before or after
the double-colon delimiter. */
String[] lineParts = fileLine.split("\\s*\\:\\:\\s*");
if(lineParts[1].equalsIgnoreCase(flightNumber)){
// At this point you could just return the line, for example:
// return fileLine;
// or you can return a string with a little more structure:
return new StringBuilder("Flight ID: ").append(lineParts[0])
.append(", Flight #: ").append(lineParts[1]).append(", From: ")
.append(lineParts[2]).append(", To: ").append(lineParts[3])
.append(", Date: ").append(lineParts[4]).toString();
}
}
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
JOptionPane.showMessageDialog(null, "<html>Flight number <font color=red><b>"
+ flightNumber + "</b></font> could not be found!</html>", "Flight Not "
+ "Found", JOptionPane.INFORMATION_MESSAGE);
return null;
}

How to search for values then modify the current value from the file if the value was found

So say for example I have this file
I want my program to search for the title and respective author using the input from the user and then ask for replacement values. Then these replacements will change the current value in the file.
This is my current implementation:
import java.io.*;
import javax.swing.*;
public class SecondChild4 extends SecondParent
{
public void edit(String sFileName, String sFileName2)
{
try
{
sFileName2 = "Second.txt";
File nfile2 = new File("Second.txt");
File file2 = new File("TempSecond.txt");
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line2 = "";
String edit2 = "";
String btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
//how to search if value was found from the file?
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
line2 = br2.readLine();
while(line2 != null){
if (line2 == null)
{
// End of File
tbw2.close();
br2.close();
}
else if(what condition to put here?)
{
System.out.println("Search found");
edit = line2.replaceAll(btitle, btitle1);
edit2 = line2.replaceAll(bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
else{
tbw1.append(line1);
tbw1.append("\n");
tbw2.write(line2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
}
file2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I made a temp file for the storage of the modified values and then delete the old file and rename the temp file according to the previous file's name. In the code I made, there are problems such as the file contents get empty(I am also saving it in csv but did not put the codes related to that here. When it comes to csv, only the first line of the previous file gets rewritten to the temp), the file don't get deleted and renamed.
I know there are lots of mistakes with my code. I'm pretty new to programming. Please help me :)
You can do it nicely by creating a book.properties file like
Title=Foo
Author=bar
Java code will be like :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SecondChild4 {
private InputStream inputStream;
public static void main(String[] args) {
SecondChild4 s = new SecondChild4();
s.getPropValues();
}
public String getPropValues() {
String result = "";
try {
Properties prop = new Properties();
String propFileName = "book.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String title = prop.getProperty("Title");
String author = prop.getProperty("Author");
result = "Book = " + author + " title " + title;
System.out.println("current book details are " + result);
// replace logic here
prop.setProperty("Title", "Hamlet");
prop.setProperty("Author", "William Shakespeare");
System.out.println("after modification");
result = "Book = " + prop.getProperty("Author") + " title " + prop.getProperty("Title");
System.out.println("cuurrent book details are " + result);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
Output :
current book details are Book = bar title Foo after modification
current book details are Book = William Shakespeare title Hamlet
Some things for you to remember while coding :
Dont put everything in try catch block just for sake of avoiding exceptions,keep only part that actually throws that exception...not whole code.
call all close methods eg: buffereader.close() in finally block
Never, never, never throw an exception , instead catch it there itself.

Read data from csv file and print unique, duplicate and invalid data separately

I have a csv file where I have to read the csv file and print unique, Duplicate and invalid elements separately.
Here is the code
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
public class InputData {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\e.csv"));
String line = null;
HashSet<String> lines = new HashSet<>();
HashSet<String> lines1 = new HashSet<>();
System.out.println("Unique List:- ");
while ((line = br.readLine()) != null)
{
{
try {
if (lines.add(line)) {
String[] part = line.split(",");
Integer.parseInt(part[0]);
System.out.println(line);
} else {
lines1.add(line);
}
} catch (NumberFormatException ne) {
System.out.println(" Invalid data:- " + ne);
}
}
}
br.close();
System.out.println("Duplicates:- " +lines1);
}
}
If the input is
101,Ron,4545,XYZ,3
102,Harry,2345,ABC,3
103,Sam,5448,DEF,3
104,John,9989,GHI,3
101,Ron,4545,XYZ,3
104,John,9989,GHI,3
105,Gang,123,HNB,3
jftdgchj;vcvuigkuj;uygf
hvykfjtucd;gfd;gfd
I get output as:-
Unique List:-
101,Ron,4545,XYZ,3
102,Harry,2345,ABC,3
103,Sam,5448,DEF,3
104,John,9989,GHI,3
105,Gang,123,HNB,3
Invalid data:- java.lang.NumberFormatException: For input string: "jftdgchj;vcvuigkuj;uygf"
Invalid data:- java.lang.NumberFormatException: For input string: "hvykfjtucd;gfd;gfd"
Duplicates:- [101,Ron,4545,XYZ,3, 104,John,9989,GHI,3]
But i want the duplicates in separate lines... Please help
You're using the default .toString() method for the HashSet like Stephen P pointed out in a comment above.
Change this:
System.out.println("Duplicates:- " +lines1);
To something like this (which uses an enhanced for-loop to iterate over the set):
for (String s : lines1) {
System.out.println("Duplicates:- " + s);
}

Array Out Of Bounds When Setting a String Value

What I want to do is set a String called nameWithYear to be equal to be movies[0] + "(" + movies[1]+")" (So "Movie Title (Year)") from text being parsed off a CSV.
Whenever I try, I am experiencing an issue where I keep on getting an array out of bounds error. I tried setting the string equal to only movies[0], it works with success. When I try to set it to movies[1] by itself, it fails. I can do a System.out that includes element [1], and it outputs just fine with no issues. So in other words, for some reason, I can only include element[0] in the string and not element[1]. So I am assuming it has something to do with declaring the value for the string. Just not sure what.
The code is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVParsing {
public String parseCSV() {
String csvFile = "C:\\Users\\RAY\\Desktop\\movies.csv";
BufferedReader br = null;
String nameWithYear = new String();
String line = "";
String csvSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
if (line.charAt(0) == '"')
{
csvSplitBy = "\",";
}
else
{
csvSplitBy = ",";
}
String[] movies = line.split(csvSplitBy);
nameWithYear = ""+ movies[0]+" ("+movies[1]+")";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nameWithYear;
}
public static void main (String[] args)
{
CSVParsing obj = new CSVParsing();
String testString = obj.parseCSV();
}
}
Note that it is not 100% complete, I am testing it in small chunks to make sure it is doing everything as I want it to do.
UPDATE: Found out that it was related to blank year entries as part of the CSV. How do I handle that? The program cuts off once it finds the year entry to be blank.
UPDATE 2: I solved it with my own but of research. I am taking the results after the split() and putting them into an ArrayList. That way, I could handle blank entries in the year column by replacing them with another value.
I guess problem is with your input file.Make sure your input is not of the form
"cauchy hep(21\10\1991) ","cauchy hep" .Notice the space between ) and " remove the space if any since:
if (line.charAt(0) == '"')
{
csvSplitBy = "\",";
}
else
{
csvSplitBy = ",";
}
csvSplitBy equals "\"," no space with the last character of string. If your file doesn't follow the pattern you specified whole line or whole file wil be treated as single string and will be stored in movies[0] .So there will no string at index 1 of movies that's why ArrayIndexOutOfBound.
Remove the space Or you can include the space the beginning " \"," again notice the space between " \"," .It will solve the problem.
split() method returns one element in the array this means that the separator does not exist in the line variable.
line.contains(csvSplitBy);// will be evaluated to false in case of one item is returned by split();
Make sure that the CSV file is comma separated .. or the data has more than one column (CSV formatted correctly )
I hope this could help!

Merging csv file

Please help me in java code. I have 2 CSV FILE
a.csv contains "zip","name","place"
b.csv contains "zip","latitude","longitude"
I need to merge the following columns with the same zip and save in another csv file
output.csv file will be:
"zip","name","place","latitude","longitude"
how am i going to code this? thank you.
I have read this a.csv but i dont know how to merge.
Here's my code in reading my first csv file
public class Merge{public static void main(String[]args ) throws Exception {
String csvFile ="a.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try{
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cFile = line.split(cvsSplitBy);
System.out.println("" + cFile[1] + " " + cFile[2] + " ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System. out. println("Done");
}
}
I think you should write the below logic to achieve this. This is just an idea.. go ahead and implement if you get any error in any specific area. You ware welcome to get back with your questions.
Read csv 1, populate an array (array 1)
Read csv 2, populate another array (array 2)
Loop both the array check the zip and merge in 3rd array.. something like below
for(loop over array 1)
// get the zip from array1
for(loop over array 2)
// get the zip from array2
if(zip1 == zip2)
then merge and put the data in another array(array3) and break this loop
Write this array3 in a new csv file

Categories