A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 15732622419 中级黑马   /  2016-7-21 18:18  /  471 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1.创建一个新文件
方法:public boolean createNewFile()
需求:在E盘创建一个test.txt文件
  
public class Test {
  
    public static void main(String[] args) throws IOException {
  
  
       File file = new File("E:\\test.txt");//实例化File类对象
  
       boolean i =file.createNewFile();//创建文件,根据给定的路径创建
  
       System.out.println(i);
  
    }
  
  
}
  
特殊声明:
         开发时要注意路径问题:
                   windows中使用反斜杠:“\
                   linux中使用正斜杠:“/
         如果要让Java程序的可移植性保持,则最好根据所在的操作系统来自动使用分隔符;
补充知识(调用静态常量)
         File.pathSeparator——“;
         File.separator——“\
完善后代码:
  
public class Test {
  
    public static void main(String[] args) throws IOException {
  
       File f = new File("d:" + File.separator + "test.txt"); // 实例化File类的对象
  
       try {
  
           f.createNewFile(); // 创建文件,根据给定的路径创建
  
       } catch (IOException e) {
  
           e.printStackTrace(); // 输出异常信息
  
       }
  
    }
  
}
  
2.删除一个指定的文件
方法:public boolean delete();
          public boolean exists(); 用来判断一个文件是否存在
  
public class Test {
  
    public static void main(String[] args) throws IOException {
  
       File f = new File("E:" + File.separator + "test.txt");// 实例化File类的对象
  
       if (f.exists()) {// 如果文件存在,则删除
  
           f.delete();// 删除文件
  
       }
  
  
    }
  
}
  
3.创建一个文件夹
方法:public boolean mkdir()
  
public class Test {
  
    public static void main(String[] args) throws IOException {
  
       File f = new File("E:" + File.separator + "test");// 实例化File类的对象
  
       f.mkdir();//创建文件夹
  
      
  
    }
  
}
  
  


欢迎访问我的CSDN博客:
http://blog.csdn.net/lwt976647637/article/details/51985297

1 个回复

正序浏览
额,谢谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马