JAVA 删除文件中的内容

JAVA 删除文件中的内容,第1张

问题提得不太清楚
如果是想要清空D:\\buytermstxt文本内容,可以使用如下代码
FileOutputStream fs = new FileOutputStream(new File("D:\\buytermstxt"));

用“”替换文件中的内容达到删除目的

import javaioInputStream;
import javaioBufferedReader;
import javaioBufferedWriter;
import javaioFileReader;
import javaioFileWriter;
import javautilScanner;
import javaioFileNotFoundException;
import javaioIOException;
public class zifutihuan
{
protected static void rep(String ch)
{
    BufferedReader bis = null;
    FileWriter bos = null;
    String s = null;
   try
   { 
     bis = new BufferedReader(new FileReader("1txt"));
      bos = new FileWriter("2txt");
while(null != (s = bisreadLine()))
   {
    s = sreplaceAll(ch,"");
    Systemoutprintln(s);
    s= s+"\r\n";
    boswrite(s);
    }
 bosclose();
  bisclose();
  s = null;
}
catch(FileNotFoundException e)
{
Systemoutprintln("未找到文件\n");
}
catch(IOException ee)
{
Systemoutprintln("aaa");
}
}
public static void main(String args[])

rep("123");
}
}

1、创建File对象File(String pathname):pathname录入时录入的路径字符串需要注意/和\的运用,但是由于java开发出的程序需要运用到不同的系统上,因此,一般以Fileseparator来代替。

2、创建File对象File(File parent,String child):此为创建文件对象的另外一种方式,parent为已创建的对象,这种情况,parent一般为文件夹的路径,child为文件的名称。

3、判断File对象是否是一个文件:isFile()返回值true为文件,false为非文件。如下程序中,由于file1对象为文件夹,非文件,返回为false;file2对象为文件,返回true。

4、文件的内容长度(占用字节):length()当前File对象所表示的文件所占用的字节量。在testFile1txt中事先录入部分数据,file2指向的File对象,内容长度为8。

5、判断文件是否存在,在硬盘创建文件前,一般需要判断硬盘中文件是否存在,如果不存在才创建文件,这样可以避免文件重复创建。

6、文件创建:createNewFile()当File对象调用文件创建方法后,硬盘中文件才会被创建。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/13348634.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-19
下一篇 2023-07-19

发表评论

登录后才能评论

评论列表(0条)

保存