java中的IO操作---File类

File类是唯一代表文件本身的对象,通过调用 File 类提供的各种方法,能够完成创建、删除文件,重命

名文件,判断文件的读写权限及是否存在,设置和查询文件的最近修改时间等操作。

File 定义了很多获取 File 对象标准属性的方法。例如:getName( )用于返回文件
名,getParent( )返回父目录名,exists( )方法在文件存在的情况下返回 true,反之返回
false。然而 File 类是不对称的,意思是虽然存在可以验证一个简单文件对象属性的很
多方法,但是没有相应的方法来改变这些属性。

package IOstream;

import java.io.*;

public class IOputStream
{
public static void main(String[] args) throws IOException 
{
File file=new File("D:\IOstream.txt"); //新建File对 
File file1=new File(".\test1.txt");
File file2=new File("D:\workspace\test\test1.txt");
System.out.println("-----默认相对路径:取得路径不同------");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
System.out.println("-----默认绝对路径:取得路径相同------");
System.out.println(file2.getPath());
System.out.println(file2.getAbsolutePath());
File file3=new File("..\src\test1.txt");
//可以看到CanonicalPath不但是全路径,而且把..或者.这样的符号解析出来。 System.out.println(file3.getAbsolutePath()); System.out.println(file3.getCanonicalPath());
if(file.exists()) //判断File对象文件是否已存在,若不是事先存在的则需要用createNewFile方法建立 { System.out.println("true"); } else { System.out.println("false"); } if(file.exists()) { file.delete(); //存在则删除 System.out.println("成功!"); } else { file.createNewFile(); //创建File对象实体 System.out.println("新建ok!"); } file.createNewFile(); int i=(int) file.length(); //获取文件内容长度 System.out.println(i); } }

运行结果:
-----默认相对路径:取得路径不同------
.	est1.txt
D:MyEclipseprojectDemoOfStreamIOStream.	est1.txt
-----默认绝对路径:取得路径相同------
D:workspace	est	est1.txt
D:workspace	est	est1.txt
D:MyEclipseprojectDemoOfStreamIOStream..src	est1.txt
D:MyEclipseprojectDemoOfStreamsrc	est1.txt
true (若不存在该文件可能为false)
成功!
0


 
原文地址:https://www.cnblogs.com/lovelifeloveme/p/3143125.html