txt文件的创建与读写

【建文件夹下的txt文件,并且按行写数据】
public class test1 {
public static void main(String[] args) throws IOException {
String directory="D:";
String fileName="myFile.txt";
File f=new File(directory,fileName);
//判断D盘是否含有myFile.txt文件
if(f.exists()){
System.out.println(f.getAbsolutePath());
           System.out.println(f.getName());
           System.out.println(f.length());
           //写操作
           FileWriter fw = new FileWriter(f,true); //设置成true就是追加               
           fw.write("ee");
           fw.write("\r\n");//换行写入
           fw.close();
           System.out.println(f.length()); 
}else{
//目录中没有myFile.txt的文件,先创建文件所在的目录
f.getParentFile().mkdirs();
try{
//创建新文件
f.createNewFile();
                //写操作
FileWriter fw = new FileWriter(f,true); //设置成true就是追加              
           fw.write("ee");
           fw.write("\r\n");
           fw.flush();
           fw.close();
           System.out.println(f.length());
}catch(IOException e){
System.out.println("创建新文件时出现了错误。。。");
e.printStackTrace();
}
}
}
}
【把txt文件按行形式读出来】
public class read {
public static void main(String[] args) throws IOException {
//读操作
        String encoding="GBK";
        File f = new File("d:/myFile.txt"); 
        if(f.isFile() && f.exists()){
        InputStreamReader read=new InputStreamReader(new FileInputStream(f), encoding);
        BufferedReader bufferedreader = new BufferedReader(read);
        String lineTXT=null;
        while((lineTXT = bufferedreader.readLine()) !=null){
        System.out.println(lineTXT.toString().trim());
        }
        read.close();
        }else{
        System.out.println("找不到指定的文件!");  
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值