java怎么创建新文件

java如何创建新文件
   在java中可以使用 java.io.file 类来创建新的文件,当初始化完了文件对象 我们就可以调用文件对象的createNewFile() 方法来创建文件, 这个方法返回一个boolean值 true表示成功, false表示失败; 当创建失败这个方法会抛出一个异常 java.io.IOException文件将会为空且0个字节

当我们通过传递一个文件名称创建文件的时候,可以是绝对路径, 不然就提供一个文件名称;也可以是相对路径; 因为file对象会从当前目录为基础目录开始查找文件

还有一点, 我们在创建文件的路径的时候应该用系统属性分隔符"file.separator"
使我们的程序可以独立夸平台使用
package com.tij.io.file;

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

public class CreateNewFile {
	
	/**
	 * this class shows how to create file in java
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		//system '\'
		String fileSeparator = System.getProperty("file.separator");
		System.out.println("fileSeparator = " + fileSeparator);
		//absolute file name with path
        String absoluteFilePath = fileSeparator+"Users"+fileSeparator+"GYJ"+fileSeparator+"file.txt";
		System.out.println("absoluteFilePath =" + absoluteFilePath);
		File file = new File(absoluteFilePath);
		
		if (file.createNewFile()) {
			System.out.println(absoluteFilePath + " File Created");
		} else {
			System.out.println("File " +absoluteFilePath+ " already exists");
		}
		
		//file name only
		file = new File("file.txt");
		if (file.createNewFile()) {
			System.out.println( "file.txt File Created in Project root directory" );
		} else {
			System.out.println("File file.txt already exists in project root directory");
		}
		
		//relative path
		file  = new File("temp");
		file.mkdir();
		String relativePath = "temp" + fileSeparator + "file.txt";
		file = new File(relativePath);
		if (file.createNewFile()) {
			System.out.println( relativePath + "File Created in Project root directory" );
		} else {
			System.out.println(relativePath + "File already exists in project root directory");
		}
	}

}
out put ==============
fileSeparator = \
absoluteFilePath =\Users\GYJ\file.txt
File \Users\GYJ\file.txt already exists
File file.txt already exists in project root directory
temp\file.txtFile already exists in project root directory