Get id number and if found, Delete it [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I have a code that Get id number and search for its records, if exist, display it.
I want if found, delete it record.
One solution for delete a line( a user record) is create another file and copy all lines without found record.
can anyone tell me another solution? (Simple solution)
my BookRecords.txt file is this:
Name Date Number
one 2002 22
two 2003 33
three 2004 44
four 2005 55
my Code to find :
String bookid=jTextField2.getText();
File f=new File("C:\\BookRecords.txt");
try{
FileReader Bfr=new FileReader(f);
BufferedReader Bbr=new BufferedReader(Bfr);
String bs;
while( (bs=Bbr.readLine()) != null ){
String[] Ust=bs.split(" ");
String Bname=Ust[0];
String Bdate=Ust[1];
String id = Ust[2];
if (id.equals(bookid.trim())
jLabel1.setText("Book Found, "+ Bname + " " + Bdate);
break;
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
please help to delete a Line(a Record)
Thanks.

Working on a single text file is - uhm - a bit strange. But I would recommend, that you create a new text file (output):
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
Only write the lines that don't match the book's ID.
while (...) {
...
if (!id.equals(bookid.trim())) {
out.println(bs);
}
}
out.close();
Later you can rename the file, if you like.

replace the entire line in the text file with a backspace character when found
\b

Related

Java read .txt file with array and save

Ok this is quite a long one but I've looked everywhere and I'm still unsure on how to do it. This is a list of students information in the classroom layout. The program is used to let a child choose a seat but once they have chose it then it should have a status update so nobody else can take it.
Columns explained - (1)Student in number order (2)Male/Female (3)Window Seat/Aisle Seat (4)With/Without table (5)Forward Seat/Backward Seat (6) Ease of Access Seat
.txt file;
01 2 true false true false
02 2 false false true false
03 1 true false true true
04 2 false false true true
05 1 true true true false
I understand they don't totally make sense but it's just an example.
How do I get the program to read through each one of these rows using an array to store all this information? for child 1,2,3's seat etc. The .txt file represents exactly what kind of seat it is as explained above. Once the array has read through I want it to be able to save each row.
If you just want to read a file and store each line seperately in an array you can do the following. Note that it's not possible to create the array beforehand as you do not know how many lines you will get.
String[] result;
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine());
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()]);
Or if you want to be able to access the columns directly:
String[][] result;
ArrayList<String[]> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine().split(" ");
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()][]);
for(String[] lineTokens) {
String studendNumber = lineTokens[0];
boolean gender = Boolean.parseBoolean(lineTokens[1]);
...
}
let's say your file name is students.txt
all u need to do is read the data and store it into an array of strings to deeal with it later so her's the stuff :
BufferedReader in = new BufferedReader(new FileReader("students.txt"));
String[][] data = new String[][6];
int i = 0;
while(in.ready()){
data[i] = bf.readLine().split(" ");//use whatever is separating the data
i++;
}
If you just want to read a text file in java, have a look at this: Reading a plain text file in Java
A saving of each row won't be possibe, it's a file, not a database. So load the file, change the data as you like, save it.
You should also think about the format... may be use XML, JSON or CSV format to store the data. There are libs which do most of the job for you...
If you are planning parallel access to your program data (more than one program instance and users, only one datafile), a simple text file is the wrong solution for your needs.

How do i create/modify the contents of a file before i create it in a Java program i have made?

Hey here is my code i have created its a simple file creation program as i have only been using java for the past 2 days. I'm only 13 so please be simple :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Filecreator
{
public static void main( String[] args )
{
Scanner read = new Scanner (System.in);
String y;
String u;
try {
System.out.println("Please enter the name of your file!");
y = read.next();
while (y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")){
System.out.println("Your Filename contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file name");
y = read.next();
}
System.out.println("Please enter the file type name");
u = read.next();
while (u.contains(".") || u.contains(",") || u.contains("{") || u.contains("}") || u.contains("#") ){
System.out.println("Your File-type name contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file-type name");
u = read.next();
}
File file = new File( y + "." + u );
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("The name of the file you have created is called " + y + file);
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you run it on a program such as Eclipse you will see the output. But i want to be able to edit the [file's] contents before i finally choose the name and the file type and then save it. Is there anyway i can do this? Thanks - George
Currently you are printing everything out to the console - this is done when you use System.out.println(...).
What you can do is to write the output somewhere else. How you can do this ? The easiest way how to do this is to Use StringBuilder:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
This is a code sample :
StringBuilder sb = new StringBuilder();
sb.append("one ");
sb.append("two");
String output = sb.toString(); // output contains string "one two"
Now you have your whole output in one string. If you look at StringBuilder documentation (link is above) you can see that there are other useful methods like insert or delete that help you to modify your output before you convert it to string (with toString method). Once all your modifications are done you can write this string to a file.
For writing a String to a file this could be helpful :
How do I save a String to a text file using Java?
This is good enough approach if you are writing small files (up to few MB). If you want to write bigger files you shouldn't store the whole string in memory before you write it to a file. In such scenarios you should create smaller strings and write them to a file. There is a good tutorial for that :
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Read lines until the line contains a special end-of-file marker. Eg, the old unix program 'mail' append all lines until a line consisting of a single '.' is read.
// insert this before reading the filename
StringBuilder content = new StringBuilder();
s = read.next();
while( !s.equals(".")) {
content.append(s);
content.append(String.format("%n"));
s = read.next();
}
The look at this: write a string into file (better answer than the other) and use that as an example of how to actually write the contents to the file, after it has been created.
p.s.
Pro-tip: I'm sure you have noticed that you have duplicated exactly the same line for checking if a filename is valid. A good programmer would notice this too and "extract" a method that does the logic in one place.
Example:
boolean isValidFilename( String s ) {
return !(y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")));
}
You may then replace the checks;
while (!isValidFilename( u )){
System.out.println("Your File-type name contains an incorrect character...etc");
}
This is good since you don't have to repeat tricky code, which means there are fewer places to do errors in. Btw, the negations (!) are there to avoid negative names (invalid=true) because you might end up with a double negation when using them (not invalid=true) and that may be a bit confusing.
You can't edit a file before you create it. You can make changes to the data you are going to write to the file once you crate it; since you control both that data and the creation of the file, there should be no problem.

How to append existing line in text file

How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite

Extracting Strings of Data from a .txt file

When I input a file and try to extract the printed strings and doubles from it, I end up extracting information on the text itself. I inserted a System.out.println into my while loop to print the lines from the file, and it also printed extra lines of text information. I'm trying to get only the written text from the file, ignoring the lines that look like:
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural"
I'm doing this so I can take the information from the file to make string arrays with them.
The purpose of this program will be to input a file with rows of information (last name(string), first name(string), account balance(double)), extract each row separately, place each row string in an Array List, sort the array list (by last name then by first name), then output a file, with the name output.txt, with the new sorted rows. The rows will be formatted last name, first name, then account balance with a single space between each. The number of rows can vary.
Input example (from a .txt file):
Smith Charles 200.000
Allen Drake 5000.00
Allen Trey 300.00
Burbis Zeik 400.00
Zan Rick 6000.00
Output example (written to a file output.txt):
Allen Drake 5000.00
Allen Trey 300.00
Burbis Zeik 400.00
Smith Charles 200.000
Zan Rick 6000.00
Thanks!
public static void main(String[] args) throws IOException {
Scanner fileName = new Scanner(System.in);
String file = fileName.next();
String input;
Scanner fileinput = null;
// File inFile = new File("c:\\csc2310\\test.txt");
File inFile = new File(file);
int i = 0;
try
{
fileinput = new Scanner(inFile);
while(fileinput.hasNext())
{
i++;
System.out.println(i);
input = fileinput.nextLine();
System.out.println(input);
}
fileinput.close();
}catch(FileNotFoundException e)
{
System.out.println(e);
System.exit(1);
}
finally
{
fileinput.close();
}
}
The problem had to do with the way that TextEdit (the Mac OS text editor) saves .text files. I wrote the same information into JEdit, and saved it with the same extension, and it eliminated all the lines of text information. Thank you for your time.
Your string is spoilt. Java while reading it will automatically pad the \ characters with \.
Hence you get
"\\pard\\tx720\\tx1440\\tx2160\\tx2880\\tx3600\\tx4320\\tx5040\\tx5760\\tx6480\\tx7200\\tx7920\\tx8640\\ql\\qnatural\\pardirnatural"
Only thing you might be able to possibly do is read the string as byte array and remove the byte equivalent of \ . Check if it is possible

Cannot read file using Scanner, never gets into loop

I am trying to read a text file in order to copy some parts of it into a new text file.
This is how I create my Scanner item :
// folder
File vMainFolder = new File(System.getProperty("user.home"),"LightDic");
if (!vMainFolder.exists() & !vMainFolder.mkdirs()) {
System.out.println("Missing LightDic folder.");
return;
}
// file
System.out.println("Enter the source file's name : ");
Scanner vSc = new Scanner(System.in);
String vNomSource = vSc.next();
Scanner vSource;
try {
vSource = new Scanner(new File(vMainFolder, vNomSource+".txt"));
} catch (final java.io.FileNotFoundException pExp) {
System.out.println("Dictionnary not found.");
return;
}
And this is how I wrote my while structure :
while (vSource.hasNextLine()) {
System.out.println("test : entering the loop");
String vMot = vSource.nextLine(); /* edit : I added this statement, which I've forgotten in my previous post */
}
When executing the program, it never prints "test : entering the loop".
Of course, this file I am testing is not empty, it is a list of words like so :
a
à
abaissa
abaissable
abaissables
abaissai
I don't understand what I did wrong, I've used this method a few times in the past.
Problem solved.
I don't really know why, but I solved the problem changing the encoding of my FRdic.txt file from ANSI to UTF-8, and then the file was read.
Thanks to everyone who tried to help me.
Is it normal that a text file encoded in ANSI is not read by the JVM ?

Categories