The format i have in the external file is
name
tel no
mob no
address
From the gui i would like to delete a contact which is in the format of above using my delete button.
i have completed the export method and was wondering if deleting would be similar,, here is my code for exporting.
{
FileOutputStream file;
PrintStream out;
try { file = new FileOutputStream("../files/example.buab", true);
out = new PrintStream(file);
out.println(txtname.getText());
out.println(txtnum.getText());
out.println(txtmob.getText());
out.println(txtadd1.getText());
System.err.println ("");
out.close();
}
catch (Exception e)
{
System.err.println ("Error in writing to file");
}
}
Do you really have to delete the contact on the file immediatly?
Usually you would do something like this:
Import the file content into your model, iaw a list of Contact objects
Apply all your edits to the model (change values, add a contact, delete a contact)
Save your edits, iaw overwrite the file with your model.
Much, much easier then trying to delete a single row on a file...
I assume you really have to use a file and cannot use a table in a database.
First of all you will have to assign an id to each contact, so that you can point to a certain contact, the id must be unique other than that it can be everything.
Why not organizing that file as an xml? Is this something your spec allows?
Easiest way is to read it fully, skip the lines which are supposed to be deleted and then write it fully back to the file, hereby overwriting the original one. But that's also the least efficient way. For best results, you need to organize your data more in a model.
Why don't you use a (embedded) database instead so that you can just go ahead with a simple SQL DELETE statement?
Related
I have one csv with one row who have diferent users (users.csv), in the other hand I also have a csv with users (users2.csv)..
The problem is that I want to "compare?" these two documents and discard users from users2.csv to users1.csv if they exist in this file.
Please ideas or advice, how could I do it??
Load the first file into a List<String> users.
Load the second file into a List<String> users2.
use apache commons-collections CollectionUtils.removeAll(Collection<E> users, Collection<?> users2)
To load a file in a list you can find inspiration here.
Et voilĂ .
This only works if the size of the files is acceptable to load in memory. Otherwise it requires another approach like sorting both files using command line sort commands and walk through both files reading line by line and decide to write to output or not.
You can use BeyondCompare to compare the two csvs. It will distinctively identify the missing user along with other data mismatch if any. In case if you want to do it programatically, you can create a user bean (and override equals method to compare username or any other you want) after copying csv into list/map of beans.
Best way I see,
1) Read both the files using Java NIO Api (That's actually very fast)separately and store them into list.
Path path = Paths.get("src/main/resources/shakespeare.txt");
try {
Files.lines(path).forEach(System.out::println);//print each line
} catch (IOException ex) {
ex.printStackTrace();//handle exception here
}
2) Compare both list using java 8 predictor.
public static List < String > filterAndGetEmployees(List < String> employees,
Predicate < String > predicate) {
return list.stream().filter(predicate).collect(Collectors. < String > toList());
}
3) If you wish to write file again , You can go like,
Path path = Paths.get("src/main/resources/shakespeare.txt");
try(BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))){
writer.write("To be, or not to be. That is the question.");
}catch(IOException ex){
ex.printStackTrace();
}
Hope this will help you..
i have a sample code to copy a file from one location to another. am using that as a backup for an SQLite database file which copies the file from My Documents folder to the desktop.. the sample code is below:
try{
DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy/MM/dd HHmmss");
String sys =System.getProperty("user.home");
String fileurl = sys+"\\Desktop\\school database backup";
File dest = new File(fileurl+date.format(java.time.LocalDateTime.now()));dest.mkdir();
String sys1 =System.getProperty("user.home");
File source = new File(sys1+"\\Documents\\hyper-DB\\intellect");
FileUtils.copyDirectory(source, dest);
JOptionPane.showMessageDialog(null,"Backup Successful");
}
catch(IOException e){
e.getMessage();
} finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
this code works perfectly on my my pc which I used to create the project. but when I install it on another user's pc. it doesn't work. and am sure its unable to locate the database in My Documents folder though its there. please what do I do to make it work on another pc. thank you
As with every programming problem there are multiple ways to solve the problem. I will try to explain a couple of ways I would solve your problem. If you are heck bent on using the copy function from FileUtils. Have the entire project in a dedicated folder, with all the files in, you can even have sub-folders, this will keep thing consistent and you won't have to worry about file permissions, like the ones found on school computers. Another way to achieve the same out come is to read the main database and copy the data to the backup database one element at a time. This can also let you have the main database in the same directory as the backup database. It wouldn't hurt to have it all in a single folder too.
What I am trying to do is write a record to new line in my text file. Every time someone clicks sign up on my program, I want to call a method that opens a file and adds a record. This is what I have now:
To open the file:
try {
l = new Formatter("chineses.txt");
System.out.println("Did create");
} catch (Exception e){
System.out.println("Did not create");
}
To add the record:
public void addRecord(){
l.format("%s", nameField.getText());
}
Every time I put in a name in the name field and click sign up in my GUI, it always replaces whatever is on the first line in the text file.
How can I make it write to the second line while retaining what is on the first line?
Have you thought about using RandomAccessFile? You can seek to the end, then write.
According to the javadoc a formater created with a single String argument will first empty the file (truncate to zero length) before writing to it. This is why your file is not appended to. The program first removes whatever is in the file and then writes the new content to it when you call l.format().
What you probably want to do is format your data to a String using Formatter(). Open your record file for appending and then write that string to the file. This link should have plenty of details on how you might do this. (I googled "java open and write a file" to find that resource)
I have an file, where I am writing data to it. I've tried googling, but all examples I have tried have just confused me more.
I am inputting data into a file, and this is happening correctly, where the items selected are being appended to the file. Where my issue is, is that I want to check whether the string being inputted already exists in the file, and if it does, I want to skip it.
The code I am using to input the data to the file is below, but I am not sure how to change it to check for a duplicate.
for (EventsObj p : boxAdapter.getBox()) {
if (p.box){
String result = p.name + " " + p.price;
try {
// open file for writing
OutputStreamWriter out= new OutputStreamWriter(openFileOutput("UserEvents.txt",MODE_APPEND));
// write the contents to the file
out.write(result);
out.write('\n');
// close the file
out.close();
}
catch (java.io.IOException e) {
//do something if an IOException occurs.
Toast.makeText(this, "Sorry Text could't be added", Toast.LENGTH_LONG).show();
}
}
}
It is getting the checkboxes ticked, then getting the name and price related to it and appending it to file. But I want to carry out a check that this does not already exist. Any help would be appreciated and I've exhausted google and tried many things.
So, if I understood your question correctly the file contains a number of strings delimited by newline.
What you want to do is to read the file contents line by line, and store the lines in a HashSet<String>. Then, you open the file for appending and append the additional string, but only if the file did not contain the string already. As the other answer suggested, you use the contains method. However, unlike the other answer I'm not suggesting to use a list of strings; instead, I'm suggesting the use of a HashSet as it's more efficient.
While reading the file contents line by line, you can perform some basic checks: does the file already contain duplicate rows? You may want to handle those by giving the user a warning that the file format is invalid. Or you may want to proceed nevertheless.
You should firstly read from the file and create a list of strings with all your inputs.
Then before adding to the file you can check if the list of strings contains the string you want to add (just make sure that the strings share the same format such that a match will be found). If it returns false add to the file, if yes don't add to the file.
Shouldn't be such a tremendous task. You can make use of the contains method.
You might need to keep the contents of the file in a String in your program. A little inefficient, but at the moment I do not see any other way but to keep track of things in your program instead of on the file.
So before you run the program which appends text to the file, the very first thing you should probably do is parse the file for all text:
File yourFile = new File("file-path-goes-here");
Scanner input = null;
try {
input = new Scanner (new FileInputStream(yourFile) );
}
catch (FileNotFoundException e) {;;;}
String textFromFile = "";
while (input.hasNextLine())
textFromFile += input.nextLine() + "\n";
//Now before adding to the file simply run something like this
if(textFromFile.indexOf("string-to-write-to-file") != -1)
;//do not write to file
else {
;//write to file and add to textFromFile
textFromFile += "string-you-added-to-file" + "\n";
}
Hope this answers your question. Let me know if something is not clear.
I want to save a Unique ID (which is a String) which gets created when I launch my Java application. Now I want to save this somewhere (I think in some file on the disk) so that when I relaunch my application I should be able to read it and use that ID.
I want to know what is the good way to saving such ID. I am thinking of creating a Properties file and save it then retrieve it from it when I relaunch application. Is there a better or standard way for this?
EDIT :
Additionally what should be the folder location for storing on the disk. Should it be relative to my execution path or some Logged-in user specific path?
1. If its the same Java application that writes or reads this String, then use Serialization, it will be in non-readable form when saved.
2. If reading and writing is from different program, then use Text file.
3. Using Property file will be also a good approach.
If your app/program needs to store more data at some point sqlite3 might be the best option for you. It is easy to implement and use.
Download sqlite3
EDIT: How many IDs will be stored in the app? If there are just a few, a textfile or property file is enough.
EDIT2: Navigate to your Documents folder on your machine and you will see folders of programs/games. Thats where you should place the file/db. However you can also store it in the installation path on your hard drive. Also make sure your user launches the app trough a shortcut, not the actual execution file
Use the FileWriter and File classes from Java.
It should be something like that:
File f = new File(your path here);
if (f.exists()){
BufferedReader br = new BufferedReader(new FileReader(your path here));
String a = br.readLine();
br.close();
}else{
FileWriter fw = new FileWriter(your path here);
fw.write(your ID String);
fw.flush();
fw.close();
I hope this is want u meant.
Best regards
edit: just noticed too late that your edited your post....