java 文件流——常用的创建文件方法

常用的创建文件方法
  • 方式一 new File(String pathname)
  • 方式二 new File(File parent, String child)
  • 方式三 new File(String parent, String child)
package OI_practice1;

import java.io.File;
import java.io.IOException;

import org.junit.Test;

/** 
* @version 2022年4月15日
* 创建文件的三种方法
*/
public class FileCreate {
	public static void main(String[] args) {
		create01();
		create02();
		create03();
	}
	
	//方式一 new File(String pathname)
	@Test
	public static void create01() {
		String filePath = "F:\\new1.txt"; // 文件路径
		File file = new File(filePath);
		
		try {
			file.createNewFile(); // 创建文件
			System.out.println("File creat ok");
		} catch (IOException e) {
			System.out.println("File creat error");
			e.printStackTrace();
		}
	}
	
	//方式二  new File(File parent, String child) //根据父目录文件 + 子路径构建
	public static void create02() {
		File parentfile = new File("F:\\");  
		String filePath = "new2.txt"; // 子路径
		File file = new File(parentfile, filePath); // 这里的创建的对象还在内存里面
		
		try {
			file.createNewFile(); //从内存的数据传入到硬盘里,真正的创建文件
			System.out.println("File creat ok");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//方式三 new  File(String parent, String child) 
	public static  void create03() {
		String parentPath = "F:\\";
		String filePath = "new3.txt";
		
		File file = new File(parentPath, filePath);
		
		try {
			file.createNewFile();
			System.out.println("File creat ok");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值