aspose file tools*
The moose likes Beginning Java and the fly likes Deleting contents from a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Deleting contents from a file" Watch "Deleting contents from a file" New topic
Author

Deleting contents from a file

Akshata Alandker
Greenhorn

Joined: Sep 11, 2012
Posts: 19
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.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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.
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

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.


Swastik
Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 186

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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

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

Joined: Mar 26, 2012
Posts: 186

Map is always a good option for searching, but I wonder what will be the key considering OP's file information!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

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

Joined: Mar 26, 2012
Posts: 186

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
Vinod Tiwari
Ranch Hand

Joined: Feb 06, 2008
Posts: 459
    
    1
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.


Vinod Tiwari | Twitter
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8008
    
  22

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Akshata Alandker
Greenhorn

Joined: Sep 11, 2012
Posts: 19
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
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3681
    
  16
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


Joanne
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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

Joined: Sep 11, 2012
Posts: 19
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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6



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

Joined: Sep 11, 2012
Posts: 19
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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

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

Joined: Sep 11, 2012
Posts: 19
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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

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

Joined: Sep 11, 2012
Posts: 19
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
Rancher

Joined: Jan 08, 2009
Posts: 1477
    
    6

You are most welcome Akshata.
Akshata Alandker
Greenhorn

Joined: Sep 11, 2012
Posts: 19
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
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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

Joined: Sep 11, 2012
Posts: 19
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
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Deleting contents from a file