Deleting a text file
Ok, I am back, again. I searched the web on how to Delete a text file completely, and came to a thread on these forums. But there was one issue, there was no answer in the thread. I know that the File class has a delete method, but I am not sure how to use it. Any help is great! Thanks guys.
Ok, I am back, again. I searched the web on how to
Delete a text file completely, and came to a thread
on these forums. But there was one issue, there was
no answer in the thread. I know that the File class
has a delete method, but I am not sure how to use it.
Any help is great! Thanks guys.You should definitely check whether the [url http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete()]Javadoc holds answers before asking such questions.
Similar Messages
-
How to delete a text file in the HP cloud
I had a text file that was created through a text (notpad type app ) on my kindle fire. I sent it to my HP printer using the Eprint app which worked great. I deleted the file from the notepad app but it still shows up in my HP cloud. How do I go about deleting it from my Eprint files ??
Hi there, can you clarify what you mean by "How do I go about deleting it from my Eprint files ??"
If its the notification message from within the ePrint app itself, then it is only a notification and a copy of the file does not get stored in the app.
Best.
If my reply helped you, feel free to click on the Kudos button (hover over the "thumbs up").
If my reply solved your problem please click on the Accepted Solution button so other Forum users may benefit from viewing the post.
I am an HP employee. -
How can I create a text file before writing sth into it?
And how to delete it afterwards??After I created and opened a file, I tried to write sth into it and then get the data from the file. However, I had to performed the second time before I could get the right data.
Would it be due to the reason that the program runs so fast before the file can be created and the data being written into it properly? -
Delete and reaname oprations on text files??
Hi all,
I wonder how we can rename and delete a text file in java?
any comment will be appreciated.
abdConsult the API (java.io.File)
You'll find the methods delete() and renameTo(). -
Hi ,
Can you send the syntax of :
1/ How can i open a text file
2/ How can i create a text file
3/ How can i write in a text file
4/ How can i delete a text file
Please advise ,
Thank you .import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close(); -
i need to delete (or replace them with white space) a few lines from a text file. I have a text file with first few lines & last few lines containing "<"or ">". I need to delete/replace with white space, the entire line. i need to do this urgently
Could some one please tell me how to do this?the file can be of size 8MB or more. i get this file
every week from a third party. So the size is not
constant. I need to remove/replace with white space,
the fist & last few lines and the rest is comma
seperated values which i need to load to database
using sqlldr. But still not sure abt how to remove
the first few lines.
i need to read this file, replace the lines as i read
them and write the replaced string back to the file &
then load the rest of lines to database.8 MByte is fairly small. Read the file a line at a time and copy to a new file only the lines you want. Should take no more than a second or so.
P.S. It will probably be a mistake if you try to edit the original file in place. -
HOw to create a text file in the given path and delete it after the use?
Hi all,
I am trying to create a text file at the given path and delete the created file after the use.
I am using following code.:
import java.io.*;
// write binary data as characters
public class RanIO {
public static void main(String f[])
// First illustrate append
String lineSep = "\n";
try {
File temp= new File("C:/Ash","cute.txt");
boolean ch=temp.createNewFile();
if(ch)
System.out.println("file created");
else
System.out.println("file Not created");
//writing to file
/* PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter("cute.txt",true)));
p.print("Emp NO");
p.close();*/
// Open fileWriter in append mode
FileWriter fos = new FileWriter(temp, true);
BufferedWriter bw = new BufferedWriter(fos);
PrintWriter pw = new PrintWriter(fos);
double d=550;
// lineSep = System.getProperty("line.separator");
pw.print("Hello");
//pw.print( lineSep );
pw.print( d );
pw.close();
boolean det=temp.delete();
if(det)
System.out.println("File deleted");
else
System.out.println("File not deleted");
} catch (IOException ioe)
System.out.println( "Append IO error:" + ioe );
My problem:
1)
I am not able to write to the file. I want to know, where i am going wrong.
It is giving error message like
"Canot resolve Symbol: temp,"
But, FileWriter Constructor should accept a File type parameter.
here temp is a file parameter.
If i am not using file=new file();
i can't delete the file after the use. i.e if i use
PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter("cute.txt",true)));
how can i delete cute.txt after the use?
2)
I am not able to write to the text file. file is created but, a blank file.
"Hello" is not written into the text file.
can anyone help me in this regard
Thanks in advance
AshviniThank you Ram,
But, i want to create a text file in Append mode.
for that i used
FileWriter fos = new FileWriter(temp,true); But, it is not accepting FileWriter constructor in
this format. if i use
FileWriter fos = new
FileWriter("c:/ash/cute.txt",true); it works fine. !!!!!Here's the javadoc
public FileWriter(File file,
boolean append)
throws IOExceptionConstructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
Throws:
IOException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
Since:
1.4
Are you using jdk.13 or lower ?
>
ONe more doubt, Does flush method deletes a file?
if not, then i need to use
File temp=new File("c:/ash/cute.txt");
FileWriter fos = new FileWriter(temp,true); //which
is again a problem
if(temp.delete())
out.println("File is deleted");
}I don't know whether i am taking it wrong ! or
anything wrong with my coding ! but, after creating
and writing data into a text file. I must delete it
as it contains confidential informations.
Regards,
Thanks.'flush' writes to a file immediately. Else you should explicitly call 'flush' to write contents from buffer to underlying source.
javadoc again
PrintWriter
public PrintWriter(Writer out,
boolean autoFlush)Create a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
cheers,
ram.
Question; What do you gain by opening a file, writing to it and deleting it in the same program ? -
By Java how to delete some lines in a text file containg some character?
Hello All,
I am having a text file [Basically It is a Sql File]. its containing some commented lines.
All i need to do is, By using a java Method I have to delete All the commented lines in That file .....
For Example if My file is like following.
/**** Commented By Kannan *********/
Select * From Employee;
go
/******************** Commented by Others ********/
Select * From DevMembers;
go
/*** Ends here **********/
And the output file would be
Select * From Employee;
go
select * From DevMembers;
go
can Anyone Help me in this regards,
Akram KannanBufferedReader should probably wrap the FileReader if you will be reading line-by-line. Same with the Writer.
And a simple -
if ( "/*".equals(record.substring(0,1) ) ... should handle the comment locations bit.
Message was edited by:
abillconsl -
How can i delete a UserName from a text file using Strings or io.
hi i m trainee
i have been assigned to make java program which deletes a UserName and
his Passwor from a Text File
i m unable to do it using the code below
plz help
do reply
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java .applet.*;
import java.io.*;
class Del extends JFrame implements ActionListener
String s2;
JTextField CWDMUserDText = new JTextField();
JButton CWDMSecDelButton = new JButton("DELETE");
JLabel CWDMUserLabel = new JLabel("USER NAME");
JPasswordField CWDMPassDText = new JPasswordField();
JLabel CWDMPassLabel = new JLabel("PASSWORD");
//String user,pass;
/* CONSTRUCTOR*/
Del()
Container contentPane=getContentPane();
contentPane.setLayout(null);
setLocation(400,200);
contentPane.add(CWDMUserDText);
contentPane.add(CWDMSecDelButton);
contentPane.add(CWDMUserLabel);
contentPane.add(CWDMPassDText);
contentPane.add(CWDMPassLabel);
CWDMUserLabel.setBounds(20,70,100,25);
CWDMPassLabel.setBounds(20,100,100,25);
CWDMUserDText.setBounds(150,70,100,25);
CWDMPassDText.setBounds(150,100,100,25);
CWDMSecDelButton.setBounds(80,135,100,25);
CWDMUserDText.addActionListener(this);
CWDMPassDText.addActionListener(this);
CWDMSecDelButton.addActionListener(this);
contentPane.setBackground(Color.CYAN);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==CWDMSecDelButton)
// user = CWDMUserDText.getText();
// pass = CWDMPassDText.getText();
// showarr();
s2 = CWDMUserDText.getText();
CWDMUserDText.setText("");
CWDMPassDText.setText("");
DelUser(s2);
public static void main(String args[])
Del myframe1= new Del();
myframe1.setSize(300,200);
myframe1.setVisible(true);
public void DelUser(String s)
//int a;
try
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String s1;
int a;
int len = s.length();
System.out.println(len);
//s2 = CWDMUserDText.getText();
while ((s1=br.readLine()) !=null)
if((a=s1.indexOf(s))>0 && (a=s1.indexOf(s))!=0)
System.out.println(a);
fr.close();
catch(FileNotFoundException e)
System.out.println("exception occured");
catch(IOException e)
System.out.println("io");
}Some tips:
1) If you are adding or deleting stuff from a text file you need to write a new, modified file and then, optionally, do something like:
rename the old file to whatever.bak or the like.
rename the new file to the old.
2) Don't depend on System.out so much on a GUI application. For example if you get an exception use javax.swing.JOptionPane to display an alert (and show the message from the exception). You can write the stack trace to System.out if you want.
3) Don't muck about with calculating bounds for screen objects, let a layout manager sort it out. I like BoxLayoutManager for most things like this.
4) For bonus points do your IO in a separate Thread. Generally you don't want anything happening in an actionPerformed method which significantly delays it's return. The method should launch a new Thread to do the job, and disable the button until the Thread finishes. -
Hi there,
I am having a real battle trying to delete data from a text file I am using. There seems to be this giant cloud with Java, where there is no real easy way to delete text from a file??
I have a JFrame with two textfields on it where you enter the username and pcname. There is a OK button once you have entered those details.
On action event I would like those two details, to be removed from the text file that has been read in.
I have a text file like this:
bob
pc1
bill
pc2
The data above gets written no problem, one at at a time using the below.
File f = new File("\\c:\\filename.txt");
String strToWrite;
try
FileOutputStream fstr = new FileOutputStream(f);
strToWrite = username1+ '\r'+'\n' ;
byte[] bytes = strToWrite.getBytes(); fstr.write(bytes);
strToWrite = pcname1 + '\r'+'\n' ;
byte[] bytes2 = strToWrite.getBytes(); fstr.write(bytes2);
strToWrite = username2+ '\r' +'\n' ;
byte[] bytes3 = strToWrite.getBytes(); fstr.write(bytes3);
strToWrite = pcname2 + '\r'+'\n' ;
byte[] bytes4 = strToWrite.getBytes(); fstr.write(bytes4);
catch (IOException e)
System.out.println("Error -- " + e.toString());
To read them back in I have made the follwoing:
BufferedReader br= null;
Count = 0;
try
br = new BufferedReader(new InputStreamReader(new FileInputStream("\\c:\\filename.txt")));
String s = "";
while((s=br.readLine()) != null )
Count = 1;
//System.out.println("Data is " + s);
inboundtext = s;
if ( Count == 1 )
break;
while((s=br.readLine()) != null )
//System.out.println("Data is " + s);
inboundtext = s;
Count = 2;
if ( Count == 2 )
break;
catch(IOException ie)
finally
try
if(br!=null) br.close();
catch(Exception e)
Now the above I know, is reading each line of the text file one at a time.
Now what I would like is that when the text that we got from the textfields, using getText(), be removed from the file without destroying the rest of the records in there? Why is it so easy to add and replace files, but not do any deleting from them?
please help!!sorry, FileOutputStream fstr = new FileOutputStream(f);
should be FileOutputStream fstr = new FileOutputStream(f, true); -
How do I delete some text in a tag in the XML file?
I need help with removing some text inside the tags so I can use it as a XMLfile
string example
Code
<Event xmlns="http://SwitchKing.Common/Entities/RESTSimplified/2010/07" >
<Description i:nil="true"/>
So these are the tags inside the file that is stopping my work.
I cant seem to find a way to remove the xmlns.... or the i:nil...
The i:nil gives of a error when trying to read the file and the xmlns stops the search for other tags in the file.
So when I have loaded the data I need to delete some text in the tags.
Help!If you want to delete photo stream photos, just deleted them from your device and they will be deleted from iCloud and your other devices. Be sure you don't want them as you cannot get them back once you delete them.
-
How to update and delete records in a text file?
Hi,
I had a text file in which contains records line by line with ',' as delimiter as I use stringtokenizer and vector to read the data.
The format in the text file likes: Name, Sex, Age.
I want to add 2 functions:
(1) update the record by name, sex or age;
(2) delete the whole line of record;
Do I need to open a temp text file to do it?
And, what is the algorithm can be suggested?
For both of them, I want to firstly read the total line numbers. Then, the line number + Name, Sex, Age will be displayed on the console window. User can choose which line of record to update or delete.
Or, user can search name in order to do that.
But, what is the backend algorithm to handle it? If I have 10 lines of record, I want to delete 7th line, the 7th line of the text file will be blanked. How can I move 8th, 9th and 10th lines of records up by one line in order to fill the blank line?
Do I need to copy the first 6 lines to a temp text file and copy the last 3 lines of records to the same temp file first? and then copy all the content of that temp file back to the original text file? If so, how can I copy the same format of the original file (with '\n') to the temp file? I need the same data structure likes Name, Sex, Age.
However, when I add records, I need to append the text in the original text file, not override it's current content.
Any advice?
Thanks
gogoIf your file is not designed to be amazingly large, then you don't need to use a temporary file -- you can just read the data into memory and manipulate it there. (Like, into a Document object or something.)
But if you are dealing with really large files, you might want to consider using a database back end instead of a text file, which is a completely different approach I know but... well, that's why databases were invented. -
Delete or update a line in a text file
Hi, I've got one problem and I hope anybody can help me.
I read a text file like this :
montext = 20204578
montext2 = 22132546
montext3 = 31321321
I want to know how I can delete or update a specific line in my text file.
thanks a lot.I read a text file like this :
montext = 20204578
montext2 = 22132546
montext3 = 31321321
I want to know how I can delete or update a specific
line in my text file.Sure. read in the file with the Readers readLine()-method in a loop; if the line it read is the one that should be removed, don't add it (or use a counter variable, if you do it by numbers) to the output String.
If it's to be replaced, replace it at that moment, then add the new line to the string.
Write back the string into the old file (don't append) and you're done.
Answer provided by Friends of the Water Cooler. Please tell forum admin via 'Discuss the JDC Web Site' forum that off-topic threads should be supported
Thanks, Geoff, good idea! -
Deleting a column in a text file using LabVIEW
Hello all,
I'm trying to delete the first column of my tab delimited text file using LabVIEW and then save it under the same file name. Can someone show me a quick way to perform this operation. Is this even possible with LabVIEW? Any help would be much appreciated.
My purpose is to automate this operation for hundreds of daily text files containing data that needs processing. I'm currently using LabVIEW 8.2.
Thanks!
-noviceLabVIEWuserIf the file is relatively small:
Read the file using the Read from Spreadsheet File VI to get 2D array.
Remove the column from the 2D array.
Write out new 2D array to new file using Write to Spreadsheet File VI.
If the file is relatively large then you will likely run into memory issues. In this case you will need to read the file in chunks. You can decide how many lines to read at a time. Use a for-loop that's set to run for the number of chunks to read (based on the total number of lines and the number of lines you want to read at a time). Hint: Quotient & Remainder function. In the loop use the Read Text File VI to read your set number of lines. Convert the lines to a 2D array delete your column, and write out that chunk of data to the new file. Rinse and repeat. -
Delete specified line in a text file
can anyone help me??
how to remove specific line in a text file using java?? thank thanksRead the file, write a new one, and when you write skip over the line you want to delete.
Maybe you are looking for
-
ClassCastException when deploying jsf war on Weblogic 10.3.2
Hello everybody, We 're having an issue when deploying jsf war on Weblogic 10.3.2 The war works fine on Tomcat 6. When deploying on Weblogic we got the following exception: java.lang.ClassCastException: weblogic.xml.jaxp.RegistryXMLReader cannot be c
-
I have had my iPad for 6 months. We recently had a power outage and my iPad was plugged in with the adapter that came with it. Since then I can not charge iPad with adapter, however I can charge it SLOWLY on my computer. Do you think the adapter g
-
Errors encountered during installation.(U44M1P7)
Every time I try to update extension manger cc I get this error. I have tried download updates 7.1 to 7.2 manually and installing but when a ne w update is released the CC app fails installation every time. Plus most of the extensions I did have are
-
BAPI_PR_CHANGE (Not Able to insert more than 3 Line Items)
Hi Friends, I have Issue with BAPI_PR_CHANGE. I could Able to insert up to 3 lines items using this BAPI but if I am Trying to Insert More Than 3 BAPI throwing Dump. Any Idea on this? Any Parameter I need to pass for more than 3 line items. Let me kn
-
Question: Trouble linking PDF in Muse
Hi. I purchased a Adobe Creative Cloud subscription for Christmas and have since been learning how to use Muse. Today, I was working on a website for a client that includes a downloadable PDF of the clients brochure. Everything works fine except that