Removing a specific line from file handling text file java - java

File RaptorsFile = new File("raptors.txt");
File tempFile = new File("raptorstemp.txt");
BufferedWriter output = new BufferedWriter (new FileWriter ("raptorstemp.txt"));
System.out.println("Please enter the following infomation");
System.out.println("Please enter the Player's Name");
String PlayerName=sc.nextLine();
System.out.println("Please enter the Player's FG%");
String FieldGoal=sc.nextLine();
System.out.println("Please enter the Player's 3P%");
String ThreePointer=sc.nextLine();
System.out.println("Please enter the Player's FT%");
String FreeThrow=sc.nextLine();
System.out.println("Please enter the Player's REB");
String Rebounds=sc.nextLine();
System.out.println("Please enter the Player's AST");
String Assists=sc.nextLine();
System.out.println("Please enter the Player's Points");
String Points=sc.nextLine();
String currentLine;
while((currentLine = Raptors.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(PlayerName+"," +FieldGoal+"," +ThreePointer+"," +FreeThrow+"," +Rebounds+"," +Assists+"," +Points)) continue;
output.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(RaptorsFile);
output.close();
System.out.println("The CarsTemp file will have the new list");
options(Raptors,s);
I am having a problem i just want the user to input only player's name, for example if he inputs Kyle Lowry i want it to delete all of Kyle Lowry's stats. Below is sample of text field.
Lou Williams,41.1,36.3,87.6,60,53,508
Kyle Lowry,44.9,35.1,81.3,160,260,702
Patrick Patterson,48.8,46.0,75.0,177,61,286
Terrence Ross,42.9,38.7,87.9,119,30,411
Jonas Valanciunas,54.2,0.0,79.2,283,16,414

So basically you loop through the file and check the beginning of each line of text to see if it starts with the user input. You can use the String method startsWith() to determine if the line starts with the user input, if it returns false, write the line to a temporary file, if it returns true, skip to the next line in the input file. When you've scanned the entire input file, close them both, rename the original to a backup file and rename the temporary file to the original file. Not a very complicated problem.

You can either use the String.startsWith() method or match to a regular expression.
Solution 1
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.startsWith(PlayerName + ",")) { // you could use continue as well, but imho it is more readable to put the output.write inside the condition
output.write(currentLine);
output.newLine();
}
}
This solution has better performance but can result in false positives
Solution 2
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.matches(PlayerName + ",\\d[\\d.+],\\d[\\d.+],\\d[\\d.+]),\\d+\\d+,\\d+\\s*") {
output.write(currentLine);
output.newLine();
}
}
This solution exactly matches your criteria but has worse performance and looks uglier.
I think Solution 1 should work well.
Please note, that I have not tested the above pieces of code.
PS: it is always a good idea to adhere to the official coding conventions, such as variable names should start with lowercase characters and so on.
PS2: You could use a PrintWriter instead of BufferedWriter, which gives you additional methods, such as println, which combines write(…) and newLine().

Related

Ask user for command including a filename confusion

In this part of my program I ask the user for a command and a filename. The command can be 'read', 'content' or 'count'. In all the different tasks I need a file. I want the user to type in the console something like:
read Alice's Adventures In Wonderland.txt
For some reason I don't get how to implement this in 1 command. Now, I'm first asking the filename and afterwards I ask what to do with it. The following example is the 'read' command which asks for a file and counts all the words in the file:
case "read":
int nrWords=countAllWords();
System.out.println("The number of words in this file is: "+nrWords+"\n");
break;
.
private static int countAllWords() throws IOException
{
Scanner input=new Scanner(System.in);
System.out.println("Please enter file name: ");
String fileName=input.nextLine();
FileInputStream inputStream=new FileInputStream(fileName);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line=bufferedReader.readLine();
int nrWords=0;
while(line!=null)
{
String[] wordsInLine=line.split(" ");
nrWords=nrWords+wordsInLine.length;
line=bufferedReader.readLine();
}
return nrWords;
}
Can somebody explain how I can fit those 2 commands into one senctence in which my code understands what relates to what?
Instead what you can do here is to use the split function to break apart your command like so:
String line = bufferedReader.readLine();
String command = line.split(" ")[0];
String fileName = line.substring(command.length);
And that way your fileName will be the rest of the String, and the command just the first element. command should be the command and fileName should be the file's name.
If you get the entire command in one input, you can parse out the first word -- understanding that this is the 'action' -- and then the rest is the filename.
So first you'd get the entire command:
Scanner input=new Scanner(System.in);
System.out.println("Please enter command: ");
String command = input.nextLine();
Then you'll want to parse out the action. It will always be the first word.
String action = command.substring(0, command.indexOf(' ')).trim();
String fileName = command.substring(command.indexOf(' ')).trim();
Now you can check what the action is and use the file as needed.
String's indexOf method will return the index of the first occurrance of the specified character. So in this case we're using it to get the index of the first space. Note that indexOf will return -1 if the character is not present, so you'll want to trap appropriately for that. (Example scenario: user just enters "read" without a filename.)

Accept arbitrary multi-line input of String type and store it in a variable

Is there any possible way to accept a arbitrary(unknown) no. of input lines of string from the user until user explicitly enters -1 and store it in a string for further manipulation.
From what I gather, you're trying to get input from a user until that user types -1. If thats the case, please see my function below.
public static void main (String[] args)
{
// Scanner is used for I/O
Scanner input = new Scanner(System.in);
// Prompt user to enter text
System.out.println("Enter something ");
// Get input from scanner by using next()
String text = input.next();
// this variable is used to store all previous entries
String storage = "";
// While the user does not enter -1, keep receiving input
// Store user text into a running total variable (storage)
while (!text.equals("-1")) {
System.out.println("You entered: " + text);
text = input.next();
storage = storage + "\n" + text
}
}
I've left comments in that code block but I'll reiterate it here. First we declare our I/O object so that we can get input from the keyboard. We then ask the user to "Enter something" and wait for the user to enter something. This process is repeated in the while loop until the user specifically types -1.
Your question makes no sense... You're talking about taking input from a user, but also reaching the end of a file, implying you are taking reading input from a file. Which is it?
If you're trying to say that for each line in a file, the user must enter something for some action to be taken, then yes, that can be done.
I'll assume you already have a File object or String containing the file path, named file.
// make a stream for the file
BufferedReader fileReader = new BufferedReader(new FileReader(file));
// make a stream for the console
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
// declare a String to store the file input
String fileInput;
// use a StringBuilder to construct the user input lines
StringBuilder inputLines = new StringBuilder();
// while there is a line to be read
while ((fileInput = fileReader.readLine()) != null) {
/*
** maybe some output here to instruct the user?
*/
// get some input from the user
String userInput = consoleReader.readLine();
// if the user wants to stop
if (userInput.equals("-1")) {
// exit the loop
break;
}
// else append the input
inputLines.append(userInput+"\r\n");
}
// close your streams
fileReader.close();
consoleReader.close();
// perform your further manipulation
doSomething(inputLines.toString());
Those classes are located in java.io.*. Also, remember to catch or have your method throw IOException.
If you want to perform your manipulation each time you have some input instead of doing it all at the end, get rid of the StringBuilder, and move doSomething(userInput) into the loop before the if statement.

Java: Skipping the first line of user input when appending a text file?

So I'm trying to accept lines of text from the user so that it can be appended to a txt file. However, after the program runs, the first line the user entered does not appear in the appended file.
Here is a portion of the code:
System.out.println("enter advice (hit return on empty line to quit):");
String advice = keyboard.nextLine();
FileWriter fw = new FileWriter(inputFile, true);
PrintWriter pw = new PrintWriter(fw);
for(int n = 1; n <= 2; ++n)
{
advice = keyboard.nextLine();
pw.print(advice);
}
pw.close();
keyboard.close();
Here is a sample run of the code:
$ java Advice
enter input filename: Advice.txt **enter**
1: fully understand the given problem
2: do analysis and design first before typing
enter advice (hit return on empty line to quit):
a **enter**
b **enter**
Thank you, goodbye!
$ cat Advice.txt
1: fully understand the given problem
2: do analysis and design first before typing
b
Any thoughts?
Thanks!
The first line the user enters is being captured but not being written to the file.
String advice = keyboard.nextLine();
When you write to the file you are taking in the next user input

reading text file and assigning strings from file to variables

I have a few problems with my code. I want to be able to read input from a text file and take the strings from each line or between spaces and assign them to variables that I will pass to an object.
My first problem is that my program misreads one of my lines and omits the first letter from a variable, and the second problem is I don't know how to make my program read two strings on the same line and assign them to different variables.
System.out.println("Input the file name of the text file you want to open:(remember .txt)");
keyboard.nextLine();
String filename=keyboard.nextLine();
FileReader freader=new FileReader(filename);
BufferedReader inputFile=new BufferedReader(freader);
courseName=inputFile.readLine();
while (inputFile.read()!= -1) {
fName=inputFile.readLine();
lName=inputFile.readLine();
officeNumber=inputFile.readLine();
}
System.out.println(fName);
Instructor inst=new Instructor(fName,lName,officeNumber);
System.out.println(inst);
inputFile.close();
}
I am not very good at using filereader and have tried to use the scanner keyboard method, but it lead me to even more errors :(
Output:
Input from a file (F) or keyboard (K):
F
Input the file name of the text file you want to open: (remember .txt)
test.txt
un bun
un bun won won's office number is null
text file:
professor messor
bun bun
won won
You have to read one line with readLine() then you say that you want to split with whitespace.
So you have to do something like this
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace
courseName = arrayLine[0]
lName=arrayLine[1];
officeNumber=arrayLine[2];
list.add(new Course(courseName,lName,officeNumber));
// you sure want do something with this create an object for example
}
// in some part br.close();
Here you have an example How to read a File
When you call read() in the condition of the while loop, the "cursor" of the BufferedReader advances one character. You don't want to do this to check if the stream can be read, you want to use the ready() method.
This is another solution using StringTokenizer
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
StringTokenizer sToken = new StringTokenizer(input, " ");
list.add(new Course(sToken.nextToken(),sToken.nextToken(),sToken.nextToken()));
}

how to not overwrite the data already in the text file when i want to add more data

this is the code i use when opening the txt file but it overwrites the data everytime i want to put in more data.
private Formatter X;
private File Y = new File("C:\\Users\\user\\workspace\\Property Charge Management System\\users.txt");
private Scanner Z;
public String[][] PCMSarray;
public boolean OpenFile() {
try{
if(Y.exists()==false){
X = new Formatter("users.txt");
}
return true;
}
catch(Exception e){
System.out.println("File has not yet been created.");
return false;
}
}
This is the code i use to write to the file but this works.
public void WriteToFilecmd(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your First name");
String Fname = input.next();
System.out.println("Please enter your Last name");
String Lname = input.next();
System.out.println("Please enter your Password");
String Password = input.next();
System.out.println("Please enter your user ID");
String ID = input.next();
System.out.println("Please enter the first address line of your Property");
String addressln1 = input.next();
System.out.println("Please enter the second address line of your Property");
String addressln2 = input.next();
System.out.println("Please enter the third address line of your Property");
String addressln3 = input.next();
System.out.println("Please enter the properties estimated market value");
String EstimatedPropertyValue = input.next();
System.out.println("Please enter your tax owed");
String Taxowed = input.next();
input.close();
X.format("%1$20s %2$20s %3$20s %4$20s %5$20s %6$20s %7$20s %8$20s %9$20s \n",Fname,Lname,Password,ID,addressln1,addressln2,addressln3,EstimatedPropertyValue,Taxowed);
}
Use a different constructor for the Formatter, one that takes a FileWriter (which is Appendable), and construct the FileWriter so that it appends to the end of the file:
// the second boolean parameter, true, marks the file for appending
FileWriter fileWriter = new FileWriter(fileName, true);
Formatter formatter = new Formatter(fileWriter);
As an aside, please learn and follow Java naming rules, else your code will not be easily understood by others (namely us!). Variable and method names should begin with lower-case letters.
Your code is a bit of a mess in a number of respects, but I think that the problem is that you are testing:
C:\\Users\\user\\workspace\\Property Charge Management System\\users.txt
but then you are opening
users.txt
... which happens to be a different file because your "current directory" is not what you think it should be.
Even if that is not what is causing your problem, you should fix it. The way the code is currently written it will break if your current directory is not "C:\Users\user\workspace\Property Charge Management System" when the code is executed.
If you really want to append to the file instead of overwriting it, then you need to use a Formatter constructor that takes an opened output stream or writer ... and supply it with a stream that has been opened in append mode.
I should also not that you've made a serious style mistake in your code. The universal rule for Java code is that variable names and method names must start with a lower-case letter. People assume that anything that starts with an upper-case letter is a class ... unless the name is ALL_CAPITALS, which is reserved for manifest constants.

Categories