stuck on how to read a file - java

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.

Related

How to select one row from multiple rows of strings and store the values separated by commars

I have a csv file thats converted each row into strings and i want a user to select a numbe 1- 5 and it would store what row the user entered.
The string that has been made from the csv file is below.
1,Mazda CX-9,7,Automatic ,Premium,150
2,VW Golf,5,Automatic ,Standard,59
3,Toyota Corolla,5,Automatic ,Premium,55
4,VW Tiguan,7,Automatic ,Premium,110
5,Ford Falcon,5,Manual,Standard,60
public static void carSelection() throws IOException{
String CSVFileName = "CarList.csv";
File file = new File(CSVFileName);
System.out.println("To make a booking:");
System.out.println(" Select the car number from the car list");
try {
//reads file
Scanner scanner = new Scanner(file);
//while the file has lines to read
while (scanner.hasNextLine()) {
// read the line to a string
String line = scanner.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Your question is not clear. But following code will ask user for a number and print the correspondig csv line.
public static void carSelection() throws IOException {
String CSVFileName = "CarList.csv";
System.out.println("To make a booking:");
System.out.println("Select the car number from the car list");
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
Stream<String> lines = Files.lines(Paths.get(CSVFileName));
int inputNr = Integer.parseInt(reader.readLine());
String line = lines.skip(inputNr - 1).findFirst().get();
System.out.println(line);
}

Deleting a specific line from a delimited text file by using user input. (Java)

This is my current code:
import java.util.*;
import java.io.*;
public class Adding_Deleting_Car extends Admin_Menu {
public void delCar() throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
I would like to delete a certain line of text from a file based on user input. For instance, this is my text file:
AB234KXAZ;Honda;Accord;1999;10000;3000;G
AB234KL34;Honda;Civic;2009;15000;4000;R
CD555SA72;Toyota;Camry;2010;11000;7000;S
FF2HHKL94;BMW;535i;2011;12000;9000;W
XX55JKA31;Ford;F150;2015;50000;5000;B
I would like the user to input the String of their choice, this will will be the first field in the column (eg. XX55JKA31), and then have that line of text deleted from the file. I've found some code online, but I've been unable to use it successfully.
My current code seems to just rewrite everything in the temporary text file, but doesn't delete it.
You are using File.renameTo, which is documented here:
https://docs.oracle.com/javase/8/docs/api/java/io/File.html#renameTo-java.io.File-
According to the documentation, it may fail if the file already exists, and you should use Files.move instead.
Here is the equivalent code with Files.move:
boolean successful;
try {
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
successful = true;
} catch(IOException e) {
successful = false;
}
Note:
Your code which searches for the VIN is also wrong. See Jure Kolenko's answer for one possible solution to that issue.
Moving forward, you should consider using an actual database to store and manipulate this type of information.
Your error lies in the
if(trimmedLine.equals(lineToRemove)) continue;
It compares the whole line to the VIN you want to remove instead of just the first part. Change that into
if(trimmedLine.startsWith(lineToRemove)) continue;
and it works. If you want to compare to a different column use String::contains instead. Also like Patrick Parker said, using Files.move instead of File::renameTo fixes the renaming problem.
Full fixed code:
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Adding_Deleting_Car{
public static void main(String... args) throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
Note that I changed the class definition not to inherit and the method definition to main(String... args), so I could compile on my system.

Reading a .csv file using scanner

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;
}
}

Reading null values from BufferedReader in command prompt input

I'm trying to read from the user's input from command line. For the input for filename, the program is supposed to exit whenever it detects that the user has submitted a blank value.
However, the program is always going to the "Inside Reading file" code, regardless of whether the user input contains anything or not. It never gets to execute the "Program will exit now" code. I've tried different ways of coding it, and all of them came back with the same results. Is there anything wrong with it?
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
while (true){
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null) {
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
System.exit(0);
}
}
add one extra condition filename.trim().length()>0 with (filename = br.readLine()) !=null. As != null will not check for whitespaces. And why you have put while(true). It is useless as per your current code.
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null && filename.trim().length()>0){
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
}
BufferedReader returns null when the end of stream is reached. It returns "" (the empty string of length 0) when the user enters a blank line.
Thus, you should change your loop condition to this:
while (!(filename = br.readLine()).equals(""))

adding objects to java queues from a data file

I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}

Categories