Reading null values from BufferedReader in command prompt input - java

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(""))

Related

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.

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.

How to remove old data from text file using user input in Java

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

Deleting Data from a file in Java

I am having an issue with deleting an old line of text and replacing it with a new line of text. Then ultimately storing it in a text file. Instead of deleting the old line, the new line is written together with the old text, which defeats the purpose of the function. For example if my data.txt file contains " i am a poet" and I want to replace this sentence with " i am actually a philosopher". The first is concatenated with the latter instead of being removed. Any help would be appreciated.
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
// String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if (go.equals("yes")) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
This is getting a little big for a comment.
If I start with a data.txt of i am a poet and call removedata("i am"); then run the program and enter she is as the new Text, then the final data.txt is she is a poet. This is working as designed - only the segment i am is replaced with she is because this is how the String.replace works. The only way to get the behavior you are describing is to enter i am actually a philosopher as the new Text, which will instead result in a final data.txt of i am actually a philosopher a poet. If you want to replace the whole line with the user specified new Text, simply change the line:
line = line.replace(s, newText);
to:
line = newText;
Otherwise, this appears to be working as intended.

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

Categories