so i have a text file that consist:
not voting/1/harold/18
not voting/2/isabel/24
this describes like not voting/number for vote/name/age. my goal is to edit not voting to voted but still keeping the other info (number for vote/name/age). the user will input the number for vote then if it exist, the not voting will automatically change to voted
here is my code:
File original = new File("C:\\voters.txt");
File temporary = new File("C:\\tempvoters.txt");
BufferedReader infile = new BufferedReader(new FileReader(original));
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));
numberforvote=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();
temporary.renameTo(original);
this works but the problem with my code is the second line (not voting/2/isabel/24) will disappear/deleted. i want everything to be the same except for the not voting in the given/entered number for vote.
Your output file gets entirely overwritten , so you have to write all lines, even those that you didn't intend to modify :
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
}
else{
outfile.println(line); // this will write the "unchanged" lines
}
outfile.flush();
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"...;
outfile.println(all);
outfile.flush();
} else {
outfile.println( line );
}
Copy to output if there's no match.
I should add that using a regex for a single string compare should be reduced to the simpler info[1].equals(numberforvote). But calling numberforvote = numberforvote.trim(); could be useful.
Move it outside the if and only change the part you need to change. That way you can change whatever you want then rebuild the line.
if(info[1].matches(numberforvote)){
into[0] = VOTED;
}
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
or clean up that ugly line
StringBuilder sb = new StringBuilder();
for (String element : info){
sb.append(element);
}
outfile.println(sb.toString());
Other Answers
You could just output the unchanged line like others have suggested
outfile.println(line);
but it's not as flexable if you want to make other changes later.
You should simplify the split and writing to:
String [] info=line.split("/",2);
if ( info.length == 2 ) {
...
outfile.println("VOTED/"+info[1]);
} else {
// input error
}
Related
I have a function that adds, searches, and deletes lines from a text file. The Search works irrelevant of case and has a .contains which allows it to work on less than the whole line. The delete function only deletes the exact match. I'm accessing an outside .txt file which is saving the changes that are made.
I tried duplicating my search code, but was unable to produce the same result. I'd also like to completely remove the line so that my table remains clean looking if I don't delete that last entry, but that's less important.
System.out.println("What would you like to delete");
Scanner deleteScanner = new Scanner(System.in);
String deleteInput = deleteScanner.nextLine();
try{
File file = new File("contacts.txt");
File temp = File.createTempFile("file", ".txt",
file.getParentFile());
BufferedReader reader = new BufferedReader(new
InputStreamReader(new FileInputStream(file)));
PrintWriter writer = new PrintWriter(new
OutputStreamWriter(new FileOutputStream(temp)));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(deleteInput, "");
writer.println(line);
}
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (IOException e){
e.printStackTrace();
}
I feel like .contains should work but I haven't been able to make it function as intended.
You could get all file lines easier by using:
List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset());
After that you can simple iterate thru the lines List and delete the whole line if it contains deleteInput:
for (String line : lines) {
if (line.contains(deleteInput)) {
lines.remove(line);
}
}
If there is a need to find the occupies ignoring case you can use toLowerCase() before each check.
I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}
I wanted to delete a line from a textfile after asking the user what he/she wants to delete but I don't know what to do next in my code.
The textfile looks like this:
1::name::mobileNum::homeNum::fax::birthday::email::website::address // line the user wants to delete
2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address
Here's my code:
public static void readFromFile(String ans, String file) throws Exception {
BufferedReader fileIn = new BufferedReader(new FileReader(file));
GetUserInput console = new GetUserInput();
String checkLine = fileIn.readLine();
while(checkLine!=null) {
String [] splitDetails = checkLine.split("::");
Contact details = new Contact(splitDetails[0], splitDetails[1], splitDetails[2], splitDetails[3], splitDetails[4], splitDetails[5], splitDetails[6], splitDetails[7], splitDetails[8]);
checkLine = fileIn.readLine();
if(ans.equals(splitDetails[0])) {
// not sure what the code will look like here.
// in this part, it should delete the line the user wants to delete in the textfile
}
}
}
So the output of the textfile should be like this:
2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address
Also, I want the line number 2 and 3 to be adjusted to 1 and 2:
1::name::mobileNum::homeNum::fax::birthday::email::website::address
2::name::mobileNum::homeNum::fax::birthday::email::website::address
How would I do this?
Here's a working code, assuming you are using Java >= 7:
public static void removeLine(String ans, String file) throws IOException {
boolean foundLine = false;
try (BufferedReader br = Files.newBufferedReader(Paths.get(file));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(file + ".tmp"))) {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split("::", 2);
if (tokens[0].equals(ans)) {
foundLine = true;
} else {
if (foundLine) {
bw.write((Integer.parseInt(tokens[0]) - 1) + "::" + tokens[1]);
} else {
bw.write(line);
}
bw.newLine();
}
}
}
Files.move(Paths.get(file + ".tmp"), Paths.get(file), StandardCopyOption.REPLACE_EXISTING);
}
It is not possible to delete a line from a file. What you need to do is read the existing file, write the contents you want to keep to a temporary file and then rename the temporary file to overwrite the input file.
Here, the temporary file is created in the same directory as the input file, with the extension .tmp added (note that you can also use Files.createTempFile for this).
For each line that is read, we check if this is the line the user wants to delete.
If it is, we update a boolean variable telling us that we just hit the line to be deleted and we do not copy this line to the temporary file.
If it is not, we have a choice:
Either we did not yet hit the line to be deleted. Then we simply copy what we read to the temporary file
Or we did and we need to decrement the first number and copy the rest of the line to the temporary file.
The current line is splitted with the help of String.split(regex, limit) (it splits the line only two times, thereby creating an array of 2 Strings: first part is the number, second part is the rest of the line).
Finally, the temporary file overwrites the input file with Files.move (we need to use the REPLACE_EXISTING option).
This is my debut question here, so I will try to be as clear as I can.
I have a sentences.txt file like this:
Galatasaray beat Juventus 1-0 last night.
I'm going to go wherever you never can find me.
Papaya is such a delicious thing to eat!
Damn lecturer never gives more than 70.
What's in your mind?
As obvious there are 5 sentences, and my objective is to write a listSize method that returns the number of sentences listed here.
public int listSize()
{
// the code is supposed to be here.
return sentence_total;}
All help is appreciated.
To read a file and count its lines, use a java.io.LineNumberReader, plugged on top of a FileReader. Call readLine() on it until it returns null, then getLineNumber() to know the last line number, and you're done !
Alternatively (Java 7+), you can use the NIO2 Files class to fully read the file at once into a List<String>, then return the size of that list.
BTW, I don't understand why your method takes that int as a parameter, it it's supposed to be the value to compute and return ?
Using LineNumberReader:
LineNumberReader reader = new LineNumberReader(new FileReader(new File("sentences.txt")));
reader.skip(Long.MAX_VALUE);
System.out.println(reader.getLineNumber() + 1); // +1 because line index starts at 0
reader.close();
use the following code to get number of lines in that file..
try {
File file = new File("filePath");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int totalLines = 0;
while((line = reader.readLine()) != null) {
totalLines++;
}
reader.close();
System.out.println(totalLines);
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
You could do:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.readAllLlines(file).size();
If you want to limit them or process them lazily:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.llines(file).limit(maxLines).collect(Collectors.counting...);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I am trying to remove a complete line from a text file, and have managed to remove the line if there is only one single unbroken line of text without spaces. If i have a space delimiter between strings it fails to remove anything.
Code as follows:
import java.io.*;
import java.util.Scanner;
public class removebooks {
// construct temporary file
public static void main(String[]args)throws IOException {
String title;
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter Title to remove from file");
title = titlerem.next ();
// construct temporary file
File inputFile = new File("books.txt");
File tempFile = new File(inputFile + "temp.txt");
BufferedReader br = new BufferedReader (new FileReader("books.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
//read from original, write to temporary and trim space, while title not found
while((line = br.readLine()) !=null) {
if(line.trim().equals(title)){
continue; }
else{
Pwr.println(line);
Pwr.flush();
}
}
// close readers and writers
br.close();
Pwr.close();
titlerem.close();
// delete book file before renaming temp
inputFile.delete();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Update succesful");
}else{
System.out.println("Update failed");
}
}
}
the text file is called books.txt and contents simply should look like:
bookone author1 subject1
booktwo author2 subject2
bookthree author3 subject3
bookfour author4 subject4
thank you any help would be appreciated
Why don't you use
if(line.trim().startsWith(title))
instead of
if(line.trim().equals(title))
because equals() is only true if both strings are equal, and startsWith() is true if line.trim() starts with title ;)
As you are reading the file line by line. You can make use of following
if(line.contains(title)){
// do something
}
In this case you will not be limited by title only.
String API
br.readLine() sets the value of variable line to "bookone author1 subject1".
Scanner.next() delimits by whitespace. You need to consolidate all your calls to Scanner.next() to a single String before checking against the lines in the file, if that is your intent.
In your case, if you typed "bookone author1 subject1", value of variable title would be "bookone" after your call to Scanner.next().