关于JAVA文件创建的问题

来源:百度知道 编辑:UC知道 时间:2024/09/23 14:39:10
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package 文件修改;
import java.io.*;
/**
*
* @author Administrator
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File file1 = new File(".\\abc.txt");
System.out.println("exist? "+file1.exists());
System.out.println("Is a File? "+file1.isFile());
System.out.println("File name ? "+file1.getName());
System.out.println("File path? "+file1.getAbsolutePath());
System.out.println("How long? "+file1.length());
System.out.println("Can Read? "+file1.canRead());
System.out.println("Can Write? "+file1.canWrite());
boolean b = file1.renameTo(n

在你的这个“package 文件修改”目录下 新建一个abc.txt
结果是这样
exist? true
Is a File? true
File name ? abc.txt
File path? D:\ellejune\workspaceSTD\Knapsack\.\abc.txt
How long? 0
Can Read? true
Can Write? true
Re-name? true: the new name is abc.txt

因为执行 File file1 = new File(".\\abc.txt");这句之后,并不是真正创建了一个文本文档。如果原本不存在这个文件的话,应该都是false的。创建文件应该用file.createNewFile()这个方法就会创建出来。在没有出来之前当然所有的返回都是false。仔细研究一下API文档对你是有好处的。

java中的File对象可以表示一个文件或文件夹。是为了操作文件而设计的。也就是说,它只是一个用来操作文件的对象。它并不代表真正的文件。你new了一个File,谁说的就创建了一个文件?
File表示的对象具体是否有磁盘文件与之相关联,是不一定的。
File对象的exists()方法正是让用户在操作前,先检查文件的存在性而设计的函数。
具体创建新文件,可以通过File对象的createNewFile()方法创建,或使用FileWriter或FileOutputStream或RandomAccessFile写,不存在时可以创建。