Reading a .csv file using scanner - java

I am working on a project that involves asking a user for their zip code. Using the zip code provided the program should loop through a .csv file to determine what city they live in. I can read the information in the .csv file but I have no idea how to loop through it to find a specific piece of information.
import java.util.Scanner;
import java.io.*;
public class DetermineCity {
public static void main(String[] args) throws IOException {
String zip = "99820,AK,ANGOON";
Scanner keyboard = new Scanner(System.in);
System.out.println("enter then name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is ");
System.out.println(line);
inputFile.close();
}
}

Use Scanner.hasNext() method to loop
String Details="";
int ZipCodeIndex=0;
String ZipCode = "10230"
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext()){
String x=inputFile.nextLine();
String[] arr=x.split(",");
if(ZipCode.equals(arr[ZipCodeIndex]))
{
Details=x;
break;
}
}

This assumes the format of your file is of the form "2301,Suburb, City, Country"
the .nextLine() function returns a String of the next line, however return null if their isn't a line. So using a while loop you can go through your file and store each line in a string.
Then using .split() method you would break this string using a delimiter ",". This would be stored in an array.
Then compare the user zip code with the first value of the array. If they match then you have an array with the city and other information. Then a break statement as you have found the city.
String suburb;
String[] lineArray;
String line = null;
while((line = inputFile.nextLine()) != null){
lineArray[] = line.split(",");
if(lineArray[0] == zipCodeString){
suburb = lineArray[1];
break;
}
}

Related

Reading txt file using scanner class and outputting 2 txt files

This is the prompt I was given
"Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name"
Here is what I have so far
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class BabyNames
{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = console.next();
System.out.println("Output file 1: ");
String outputBoysNames = console.next();
System.out.println("Output file 2: ");
String outputGirlsNames = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName); // creates variable that reads from txt
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputBoysNames); // writes to output file (variable name)
PrintWriter out2 = new PrintWriter(outputGirlsNames);
// Read the input and write the output
while (in.hasNextLine()) {
String A = in.next();
String B = in.next();
String C = in.next();
String D = in.next();
String E = in.next();
String F = in.next();
String G = in.next();
out.printf(B);
out2.print(E);
}
in.close(); // Prevents this file is being used error
out.close();
out2.close();
}
}
I would assume that I would need to input the data from the text file into an array. Each token is separated by a space. I don't know how to approach this. Also, after the array is set up would I need to change the out.printf() and out2.printf() to an if loop to put the tokens I want into their respective txt file.
Example line from input txt file
1 Michael 462085 2.2506 Jessica 302962 1.5436

I want to take user input in string and write that string in a text file using java. But there is a problem

import java.io.*;
public class FileHandlingReadingWriting {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
FileWriter fWrite = new FileWriter("IOPinJava.txt");
String input = "";
System.out.println("Enter data to be entered in the string\n");
input = sc.next();
String i = input;
fWrite.write(i);
fWrite.flush();
fWrite.close();
}
}
when I execute this code and enter a string, only first word of the string gets written in the file. If the string is "This is a text", then only "This" gets written to the text file.
You aren't reading in the entire line with your scanner. Try input = sc.nextLine()

parsing CSV file in Java with skipping the next row if is the first field is empty

I am using Java, and I have a CSV file that consists of 10 column and 5 rows. I would like to parse it into another CSV file with the this condition. if the first cell from any row is empty, skip that row, and jump to the next and so on. My code only reads all the rows and prints them, I want to have that condition and write into another CSV file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CSV {
public static void main(String[] args) throws FileNotFoundException {
String x;
Scanner scanner = new Scanner(new File("Book1.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next());
}
scanner.close();
}
}
Example:
see the attached image please.
Instead of delimiting the whole file, delimit line by line:
public static void main(String[] args) throws FileNotFoundException {
String x;
Scanner scanner = new Scanner(new File("Book1.csv"));
while(scanner.hasNextLine()){ // If there is another line in the file
x = scanner.nextLine(); // Extract that line
String[] values = x.split(","); // Split that line at the commas
if (!values[0].equals("")) { // If the first value is not equal to empty
System.out.print(x); // Print the line
}
}
scanner.close();
}
You can take advantage of the fact that each record is a different line. So, instead of using Scanner class directly over the File, you can retrieve full lines with BufferedReader#readLine():
BufferedReader br = new BufferedReader(new FileReader("Book1.csv"));
String myLine = br.readLine();
while (myLine != null) {
// do whatever you want with the line
// read new line
myLine = br.readLine();
}
So that myLine contains Strings like the following:
"John,M,Mi,1111,US,OR,..."
",David,criss,2222,US,MI,..."
Once you have a line, trim() it and check if the first character is your delimiter. In that case, the line should be ignored.
myLine = myLine.trim();
if (",".equals(myLine.at(0))) {
// First field empty. Ignore
} else {
// First field not empty. Write to new file
}

stuck on how to read a file

help im stuck.. we are to make two programs the 1st one we ask the user to input how many employees, 1st name, lastname, id,..then store it into a file called names.db. ...i was able to get this done...im stuck on the 2nd program...which suppose to do this....retrieve the employee database by asking the user to input the employees 1st name and if the employee is found then print that info...if not then print not found.
import java.util.Scanner;
import java.io.*;
public class RetrieveInfo
{
public static void main(String[] args) throws IOException
{
//create scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//open file
File file = new File("Employee.db");
Scanner inputFile = new Scanner(file);
//ask for employee name
System.out.print("enter the name of the employee. ");
String firstName =keyboard.nextLine();
//here is where im stuck...read the file and check of the empoyee is
here. We are learning about loops some im pretty sure its going to be a loop
}
}
You should probably get through your lines and if the data is in the current line then print it. After reading your file :
String expectedemployee = null
for(String line : Files.readAllLines(Paths.get("/path/to/file.txt")) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
if(expectedemployee != null) {
// print
} else {
// you don't have any employee corresponding
}
Or you can use BufferedReader.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null || expectedemployee != null) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
}
Using Database rather than file would be better for this type.if you want files then you should try with Object Input/Output Stream.

Java Delete Line from File

the code below is from a reference i saw online, so there might be some similarities i'm trying to implement the code to remove an entire line based on the 1st field in this instance it is (aaaa or bbbb) the file which has a delimiter "|", but it is not working. Hope someone can advise me on this. Do i need to split the line first? or my method is wrong?
data in player.dat (e.g)
bbbb|aaaaa|cccc
aaaa|bbbbbb|cccc
Code is below
public class testcode {
public static void main(String[] args)throws IOException
{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
Scanner UserInput = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserIn = UserInput.nextLine();
String lineToRemove = UserIn;
String currentLine;
while((currentLine = read.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
write.write(currentLine + System.getProperty("line.separator"));
}
write.close();
read.close();
boolean success = tempFile.renameTo(inputFile);
}
}
Your code compares the entire line it reads from the file to the user name the user enters, but you say in your question that you actually only want to compare to the first part up to the first pipe (|). Your code doesn't do that.
What you need to do is read the line from the file, get the part of the string up to the first pipe symbol (split the string) and skip the line based on comparing the first part of the split string to the lineToRemove variable.
To make it easier, you could also add the pipe symbol to the user input and then do this:
string lineToRemove = UserIn + "|";
...
if (trimmedLine.startsWith(lineToRemove)) continue;
This spares you from splitting the string.
I'm currently not sure whether UserInput.nextLine(); returns the newline character or not. To be safe here, you could change the above to:
string lineToRemove = UserIn.trim() + "|";

Categories