自己总结的Java实现文件的读写操作

做个笔记,针对java 的file的操作

 1.根据文件名及字符串,写文件

public   static   boolean  writeJiang(String content,String path,String name) {
        
try{
            File file 
= new File(path);
            System.out.println(
"文件的路径是:" + file+"/"+name);
            BufferedWriter fileout 
= new BufferedWriter(new FileWriter(file+"/"+name,true));
            fileout.write(content);
            fileout.write(
" ");
            fileout.flush();
            fileout.close();
        }

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

        System.out.println(
"写文件完毕");
        
return true;
    }
 

 

2.读文件,返回字符串

public   static  String readTxt(String path) {
        String array 
= "";
        
        
try{
            
//读取文本文件
            File file = new File(path);        
            FileInputStream rdf 
= new FileInputStream(file);
            
byte[] s = new byte[rdf.available()];
            
int b = rdf.available();
            
while((b=rdf.read(s, 0, b))!=-1){
                String content 
= new String(s,0,b);
                array 
= array+content;
            }

            rdf.close();
        }

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

        
return array;
    }
 

 

3.删除文件中某一行.ID是行号,path+name=File

 

public   static   int  deleteTxt(String path,String name, int  id) {
        
int result = 0;
        String content 
= "";
        
try{
            
//读取文件
            content = readTxt(path + "/" + name);
            System.out.println(path 
+ "/" + name);
            
            System.out.println(
"未删除记录之前得是:" +  content);
            
            
//删除某一行
            String[] a = content.split(" ");
            StringBuffer d 
= new StringBuffer();
            
for (int j = 0; j < a.length; j++{
                
if (j != id)
                    d.append(a[j]).append(
" ");
            }

            System.out.println(
"删除记录之后的为:" + d.toString());
            
            
//将修改后的写入文件
            writeNewTxt(d.toString(),path,name);
            
            result 
= 1;
        }

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

        
return result;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值