• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Deleting contents from a file

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
How can i delete contents of a file, for instance
1,Akshata,birthday,11-12-2012,04:30,Bangalore
2,Asha,wedding,05-05-2012,05:00,Bangalore
3,xyz,meeting,12-05-2012,12:00,Delhi
4,school,getTogether,12-12-2012,08:00,Bangalore
5,company,birthday,04-03-2012,03:00,Bangalore ,

these are few events which i have stored in a file, now i want to delete a particular event with id - 1, any suggestions will be help , thanks.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do you mean to write a Java program to do the deletion?
You can read the file line by line, copying the desired lines to a new file.
There was a thread about a similar problem about a week ago; please search. The OP was told to rename the new file to match the name of the old file. I can’t remember any more details offhand. Sorry.
 
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This may not be a very optimal solution. But you can use map where you can store the id as key and the other part as values. Now you can remove the desired key from map and rewrite the map contents back to the file.
 
Ranch Hand
Posts: 233
1
Eclipse IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The basic solution to this is to write code lines to find the pattern and leaving it, write all other contents to a new temp file, and delete the priginal file and rename the temp file to original's name. As Campbell emphasized, you can find the same problem in many posts if you do a search.
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just wondering what is wrong in using a memory variable as I mentioned map, instead of file? Will using the file optimize the solution?
 
Rajdeep Biswas
Ranch Hand
Posts: 233
1
Eclipse IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Map is always a good option for searching, but I wonder what will be the key considering OP's file information!
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The quickest way is probably to use a text editor and the delete key, but I think that is not the desired solution
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As per op's file information the first column seems to be the id and it seems to be unique.

now i want to delete a particular event with id - 1

 
Rajdeep Biswas
Ranch Hand
Posts: 233
1
Eclipse IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Swastik Dey wrote:As per op's file information the first column seems to be the id and it seems to be unique.

now i want to delete a particular event with id - 1


Yes, my part on missing it! I thought it as some line number
 
Ranch Hand
Posts: 466
1
IntelliJ IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with solution proposed by Campbell Ritchie. You read content line by line (use tokenizer to get id value) and then write required data (where id NOT EQUAL TO -1) onto new temp file and finally overwrite the main file.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Swastik Dey wrote:Just wondering what is wrong in using a memory variable as I mentioned map, instead of file? Will using the file optimize the solution?


It really depends on what needs to be done. My first instinct is generally the same as yours: ie, convert the file into a Java structure that makes sense. Then you can update it as much as you like before you write it back out. If all updates need to be persisted, I'd probably choose a database rather than a file though.

For a file organised by lines, a Map might be overkill: a List or an array may be all you need.

Winston
 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks every one.. I am using the same technique as many suggested, using a temp file and store the contents other then the one to be deleted, i am getting some kind of exception in this, my code is

the exception m getting is,
java.io.IOException: Stream closed

at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at com.simpragma.oop.dao.EventManagerDao.deleteEvent(EventManagerDao.java:177)
at com.simpragma.oop.EventManager.deleteEvent(EventManager.java:41)
at com.simpragma.oop.EventManagerMain.main(EventManagerMain.java:119)

the error is in this line.. while((line = reader.readLine())!=null), please help me on this
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The exception is saying that the stream is closed so you need to look at where you close your stream.

Edit: And now that Jesper has added CodeTags the problem should be more obvious to you
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Vinod Tiwari wrote: . . . use tokenizer to get id value . . .

No, don’t use a tokeniser. Read its documentation and it tells you why.

You can split the input into a String[] using "," as a delimiter, as OP has shown. If you look up regex tutorials, you find you cannot split on "." because it is a meta‑character, but the comma isn’t.
Agree with Winston that is is probably better to move the entire data into a database.
I would suggest you divide those methods into several methods; you should let each method do one thing only.
You don’t need to flush your writer; if you look here it will tell you why.
I am not sure why you are suffering that Exception. Dividing up the code into several methods will make it easier to localise.
Are you sure you are writing the desired lines to the new file? I suspect you are writing the unwanted lines only.
 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello everyone,

I have tried to modify the method and now it is not showing any exception, but still am not able to get the required result, this method should add all the lines in the file except the line of which id is passed as parameter,
but it is not doing the thing, its printing all the lines in the file again, here is my code

public void deleteEvent(int id){

List<String> newList = new ArrayList<String>();
try{

File file = new File("C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt");
FileInputStream fstream = new FileInputStream(file);

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line= null;
while((line = reader.readLine())!=null){
String[] array = line.split(CSV_SEPARATOR);
for(int i = 0; i<array.length; i++){
if(!array[i].equals(id)){

newList.add(line);

}

}
}
System.out.println(newList);
reader.close();
}

catch(Exception e){
e.printStackTrace();
}



String lines=null;
try {
FileWriter filestream = new FileWriter(("C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt"),true);
BufferedWriter out = new BufferedWriter(filestream);

//for (String dataLine : newList) {
int i=0;

for( i = 0; i< newList.size(); i++){
lines = newList.get(i);

}
//System.out.println(lines);
out.write(lines);
out.newLine();
out.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

can any one tell me where my logic is wrong? thanks..
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


If I am not wrong, passing true as the last argument opens the file in append mode, but as per your requirement you need to open the file in overwrite mode.

Following two lines should come inside the for loop

 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
appending is not the issue, i have problem in this line
if ( !array[i].equals(id)){

newList.add(line);

}

when i say -
if( array[i].equals(id)){

newList.add(line);

} it takes the line specified by the id, but when i say " !array[i] " it is taking all the lines in the file without excluding the line with - id .
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Appending is an obvious issue, even if you write some modified contents from list it will retain the existing contents and append the modified contents. However you may wish to take a look on the following code, jsu change the file path.

 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi, I have tried even this also, but result is the same, its adding all the lines from file to the list. the line with ID is also added to the list. I don't want to add that line, except the line with id all other lines should be added to the list
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
FileWriter filestream = new FileWriter(("C:/code/data.txt"),false);

What do you have as the last parameter, true or false? Recreate the data file once again, and try with the code I pasted once again.
 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Swastik Dey, that was of great help, actually i was passing parameter as int so it was not deleting the line, not I am able to do it... thank you so much
 
Swastik Dey
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are most welcome Akshata.
 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello everyone,
I have another issue in managing file, i have a method which fetches events by their type, say i give input as birthday, it prints all the birthday events from the file to my console.
The return type of this method is a List<String> and so it returns the string, and this method is in my DAO layer, I am calling this method in the service layer fetch method and the list is printed in my ui which is main() method for time being, and I have a condition not to use any system.out statement in service nor DAO methods.
my problem is, if the event does not exist in my file, how to print user friendly message "no such event found", and where? can a method have multiple returns?

here is my code

public List<String> fetchEventByType(String type) {
logger.info("Entering method fetchEventByType().");
List<String> newList = new ArrayList<String>();


try {
// Open the file that is the first
// command line parameter
File file = new File(
"C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt");
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] strArray = strLine.split(CSV_SEPARATOR);

// for (int i = 0; i < strArray.length; i++) {

if (strArray[2].equalsIgnoreCase(type)) {

newList.add(strLine);

break;
}
}

// }
in.close();
} catch (Exception e) {
// Catch exception if any
System.out.println("event of this type does not exist");
// System.err.println("Error: " + e.getMessage());
}
logger.info("exiting the method fetchEventsByType()");
return newList;
}

this is my service layer method
public List<String> fetchEventByType(String type) throws Exception{
logger.info("entering the method fetchEventByType()");
List<String> list = new ArrayList<String>();
list = dao.fetchEventByType(type);
logger.info("exiting the method fetchEventByType()");
return list;
}

and here is my main() method in which this method is called

case 3:

String events = null;
System.out.println("enter the type of event you want to fetch");
String type = input.next();
list = manager.fetchEventByType(type);

for(int i=0; i<list.size(); i++){
events = list.get(i);
System.out.println(events);

}
break;



these are my events in file
1,Akshata,birthday,11-12-2012,04:30,Bangalore
2,Asha,wedding,05-05-2012,05:00,Bangalore
3,xyz,meeting,12-05-2012,12:00,Delhi
4,school,getTogether,12-12-2012,08:00,Bangalore

if user enters some conference event, i should be able to print message from main. how can i do it?
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Work out how you intend to add a new event to your file, and how you would display the new event. But before you do that, there is a bit of hardware getting in the way. It is a black wire and it runs from your computer to the wall. Remove that wire, then work out how to do it in plain English (or other “natural” language) on a sheet of paper. Once you have done that, you should find it quite easy to convert to code.
 
Akshata Alandker
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, but I din't understand what you are trying to say, Campbell Ritchie. I just want to know how to print message from main() method when the event is not found in the file, because my method is in another package and I am calling it in main() method in other class and displaying the returns.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Stage 1: turn off computer.
Stage 2: find sheet of paper.
Stage 3: write down in simple ordinary language how you intend to do it.
 
Think of how stupid the average person is. And how half of them are stupider than that. But who reads this tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic