Java 输入/输出——File类
File类是java.io包下代表与平台无关的文件和目录,也就是说,如果希望在程序中操作文件和目录,都可以通过File类来完成。值得指出的是,不管是文件还是目录都是使用File来操作的,File能新建、删除、重命名文件和目录,File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
File类相关的方法参考链接:https://docs.oracle.com/javase/9/docs/api/overview-summary.html
Field Summary
Fields Modifier and Type Field Description static StringpathSeparatorThe system-dependent path-separator character, represented as a string for convenience.static charpathSeparatorCharThe system-dependent path-separator character.static StringseparatorThe system-dependent default name-separator character, represented as a string for convenience.static charseparatorCharThe system-dependent default name-separator character.
Constructor Summary
Constructors Constructor Description File(File parent, String child)Creates a newFileinstance from a parent abstract pathname and a child pathname string.File(String pathname)Creates a newFileinstance by converting the given pathname string into an abstract pathname.File(String parent, String child)Creates a newFileinstance from a parent pathname string and a child pathname string.File(URI uri)Creates a newFileinstance by converting the givenfile:URI into an abstract pathname.
Method Summary
All MethodsStatic MethodsInstance MethodsConcrete MethodsDeprecated Methods Modifier and Type Method Description booleancanExecute()Tests whether the application can execute the file denoted by this abstract pathname.booleancanRead()Tests whether the application can read the file denoted by this abstract pathname.booleancanWrite()Tests whether the application can modify the file denoted by this abstract pathname.intcompareTo(File pathname)Compares two abstract pathnames lexicographically.booleancreateNewFile()Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.static FilecreateTempFile(String prefix,String suffix)Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.static FilecreateTempFile(String prefix,String suffix,File directory)Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.booleandelete()Deletes the file or directory denoted by this abstract pathname.voiddeleteOnExit()Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.booleanequals(Object obj)Tests this abstract pathname for equality with the given object.booleanexists()Tests whether the file or directory denoted by this abstract pathname exists.FilegetAbsoluteFile()Returns the absolute form of this abstract pathname.StringgetAbsolutePath()Returns the absolute pathname string of this abstract pathname.FilegetCanonicalFile()Returns the canonical form of this abstract pathname.StringgetCanonicalPath()Returns the canonical pathname string of this abstract pathname.longgetFreeSpace()Returns the number of unallocated bytes in the partition named by this abstract path name.StringgetName()Returns the name of the file or directory denoted by this abstract pathname.StringgetParent()Returns the pathname string of this abstract pathname's parent, ornullif this pathname does not name a parent directory.FilegetParentFile()Returns the abstract pathname of this abstract pathname's parent, ornullif this pathname does not name a parent directory.StringgetPath()Converts this abstract pathname into a pathname string.longgetTotalSpace()Returns the size of the partition named by this abstract pathname.longgetUsableSpace()Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.inthashCode()Computes a hash code for this abstract pathname.booleanisAbsolute()Tests whether this abstract pathname is absolute.booleanisDirectory()Tests whether the file denoted by this abstract pathname is a directory.booleanisFile()Tests whether the file denoted by this abstract pathname is a normal file.booleanisHidden()Tests whether the file named by this abstract pathname is a hidden file.longlastModified()Returns the time that the file denoted by this abstract pathname was last modified.longlength()Returns the length of the file denoted by this abstract pathname.String[]list()Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.String[]list(FilenameFilter filter)Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.File[]listFiles()Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.File[]listFiles(FileFilter filter)Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.File[]listFiles(FilenameFilter filter)Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.static File[]listRoots()List the available filesystem roots.booleanmkdir()Creates the directory named by this abstract pathname.booleanmkdirs()Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.booleanrenameTo(File dest)Renames the file denoted by this abstract pathname.booleansetExecutable(boolean executable)A convenience method to set the owner's execute permission for this abstract pathname.booleansetExecutable(boolean executable, boolean ownerOnly)Sets the owner's or everybody's execute permission for this abstract pathname.booleansetLastModified(long time)Sets the last-modified time of the file or directory named by this abstract pathname.booleansetReadable(boolean readable)A convenience method to set the owner's read permission for this abstract pathname.booleansetReadable(boolean readable, boolean ownerOnly)Sets the owner's or everybody's read permission for this abstract pathname.booleansetReadOnly()Marks the file or directory named by this abstract pathname so that only read operations are allowed.booleansetWritable(boolean writable)A convenience method to set the owner's write permission for this abstract pathname.booleansetWritable(boolean writable, boolean ownerOnly)Sets the owner's or everybody's write permission for this abstract pathname.PathtoPath()Returns ajava.nio.file.Pathobject constructed from the this abstract path.StringtoString()Returns the pathname string of this abstract pathname.URItoURI()Constructs afile:URI that represents this abstract pathname.URLtoURL()
1、访问文件和目录
package com.zyjhandsome.io;
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException
{
// 以当前路径来创建一个File对象
File file = new File(".");
// 直接获取文件名, 输出一点
System.out.println(file.getName());
// 获取相对路径的父路径可能出错, 下面代码输出null
System.out.println(file.getParent());
// 获取绝对路径
System.out.println(file.getAbsoluteFile());
// 获取绝对路径
System.out.println(file.getAbsoluteFile().getParent());
// 当前路径下创建一个临时文件
File tmpFile = File.createTempFile("aaa", ".txt", file);
// 指定当JVM退出时候删除该文件
tmpFile.deleteOnExit();
// 以系统当前时间作为新文件名来创建新文件
File newFile = new File(System.currentTimeMillis() + "");
System.out.println("newFile对象是否存在1: " + newFile.exists());
// 以指定newFile对象来创建一个文件
newFile.createNewFile();
System.out.println("newFile对象是否存在2: " + newFile.exists());
// 以newFile对象来创建一个目录,因为newFile已经存在,所以下面方法返回false, 即无法创建该目录
System.out.println("newFile.mkdir():" + newFile.mkdir());
System.out.println("----------------------");
// 使用list()方法列出当前路径下的所有文件和路径
String[] fileList = file.list();
for (String fileName : fileList)
{
System.out.println(fileName);
}
System.out.println("----------------------");
// listRoots()静态方法列出所有的磁盘根路径
File[] roots = File.listRoots();
System.out.println("====系统所有根路径如下====");
for (File root : roots)
{
System.out.println(root);
}
}
}
.
null
D:\zhaoyingjun\eclipse-workspace\CollectionTest\.
D:\zhaoyingjun\eclipse-workspace\CollectionTest
newFile对象是否存在1: false
newFile对象是否存在2: true
newFile.mkdir():false
----------------------
.classpath
.project
.settings
1537712414564
1537712424492
1537712893895
1537712926829
1537712940906
1537713158525
1537713167968
1537774060515
aaa1610208071466755969.txt
bin
src
----------------------
====系统所有根路径如下====
C:\
D:\
2、文件过滤器
在File类的list()方法中可以接收一个FilenameFilter参数,通过该参数可以只列出符合条件的文件。这里的FilenameFilter接口和javax.swing.filechooser包下的FileFilter抽象类的功能非常相似,可以把FileFilter当成是FilenameFilter的实现类。
FilenameFilter接口里包含了一个accept(File dir, String name)方法,该方法将依次对指定File的所有子目录或者文件进行迭代,如果该方法返回true,则list()方法会列出该子目录或者文件。
package com.zyjhandsome.io;
import java.io.*;
public class FilenameFilterTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File(".");
// 使用Lambda表达式(目标类型是FilenameFilter)实现文件过滤器
// 如果文件名以.java结尾, 或者文件对应一个路径,则返回true
String[] nameList = file.list((dir, name) ->
name.endsWith(".java") || new File(name).isDirectory());
for (String name : nameList)
{
System.out.println(name);
}
}
}
.settings
bin
src
Java 输入/输出——File类的更多相关文章
- 第15章-输入/输出 --- File类
(一) Java的IO通过java.io包下的类和接口来支持,在java.io包下主要包括输入.输出两种IO流. 每种输入.输出流又分为字节流和字符流两大类: (1)字节流以字节为单位来处理输入.输出 ...
- I/O(输入/输出)---File类
File:表示文件与目录.用它来对文件或目录进行基本操作,它可以查出文件的基本相关信息,比如:名称.最后的修改日期.文件大小. 使用File类操作文件和目录属性步骤: 1.引入File类 import ...
- Java 输入/输出 反射
Java 输入/输出 反射 输入输出和反射 一.数据流的基本概念 流一般分为 ( Input Stream ) 和输出流 ( Output Stream ) 两类,但这种划分并不是绝对的.比如一 ...
- Java学习:File类
Java学习:File类 File类的概述 重点:记住这三个单词 绝对路径和相对路径 File类的构造方法 File类判断功能的方法 File类创建删除功能的方法 File类获取(文件夹)目录和文件夹 ...
- java中的File类
File类 java中的File类其实和文件并没有多大关系,它更像一个对文件路径描述的类.它即可以代表某个路径下的特定文件,也可以用来表示该路径的下的所有文件,所以我们不要被它的表象所迷惑.对文件的真 ...
- Java输入/输出教程
Java输入/输出(I/O)处理从源读取数据并将数据写入目标.通常,读取存储在文件中的数据或使用I/O将数据写入到文件中. java.io和java.nio包中包含处理输入/输出的Java类.java ...
- java学习一目了然——File类文件处理
java学习一目了然--File类文件处理 File类(java.io.File) 构造函数: File(String path) File(String parent,String child) F ...
- Java学习笔记——File类之文件管理和读写操作、下载图片
Java学习笔记——File类之文件管理和读写操作.下载图片 File类的总结: 1.文件和文件夹的创建 2.文件的读取 3.文件的写入 4.文件的复制(字符流.字节流.处理流) 5.以图片地址下载图 ...
- Java基础之File类的使用
Java基础之File类的使用 1.File类的构造方法和常用方法 2.对File中listFile(FileNameFilter name)学习 3.与File文件类相关的实现 File类的构造方法 ...
随机推荐
- flash初步尝试
1.pip install flask 验证 from flask import Flask 2.pip install sqlalchemy 3. pip install flask-sqlal ...
- [APM] 2个实例+5个维度解读APM技术
为了加深EGO会员之间的相互了解,同时也为大家提供更多线上相互学习交流的机会,EGO正式启动会员群线上分享活动.本文是根据陈靖华分享主题“APM的价值”的内容整理而成. 第二期分享嘉宾:陈靖华,EGO ...
- 【Android】Eclipse性能优化,快捷方式,文档注释
快捷方式 方法注释的快捷键:ALT + SHIFT +J 格式化:Ctrl+Shift+F 把当前选中的文本全部变味大写:Ctrl+Shift+X 把当前选中的文本全部变为小写:Ctrl+Shift+ ...
- 【emWin】例程二十:窗口对象——Dropdown
简介: DROPDOWN 小工具用于从具有若干栏的列表中选择一个元素,它以非打开状态显示当前选择的项目.如果用户打开DROPDOWN 小工具,就会出现一个选择新项目的LISTBOX. 触摸校准(上电可 ...
- var_dump
1:var_dump 主要输出类型和.长度和变量的值: 2: var_dump() 能打印出类型print_r() 只能打出值echo() 是正常输出...需要精确调试的时候用 var_dump(); ...
- java中的数据加密3 非对称加密
非对称加密也加公钥加密,不对称算法使用一对密钥对,一个公钥,一个私钥,使用公钥加密的数据,只有私钥能解开(可用于加密):同时,使用私钥加密的数据,只有公钥能解开(签名).但是速度很慢(比私钥加密慢10 ...
- Oracle分析函数-排序排列(rank、dense_rank、row_number、ntile)
(1)rank函数返回一个唯一的值,除非遇到相同的数据时,此时所有相同数据的排名是一样的,同时会在最后一条相同记录和下一条不同记录的排名之间空出排名. (2)dense_rank函数返回一个唯一的值, ...
- 第三百九十三节,Django+Xadmin打造上线标准的在线教育平台—Xadmin后台进阶开发配置
第三百九十三节,Django+Xadmin打造上线标准的在线教育平台—Xadmin后台进阶开发配置 设置后台某个字段的排序规则 在当前APP里的adminx.py文件里的数据表管理器里设置 order ...
- laravel5.4中验证与错误提示设置
1.对于交互提交数据,验证如: #验证 $this->validate(\request(),[ 'title' => 'required|string|min:3|max:20', 'c ...
- Scala学习笔记(四):apply方法说明
当scala中类或者对象有一个主要用途的时候,apply方法就是一个很好地语法糖.请看下面一个简单的例子: class Foo(foo: String) {} object Foo { def app ...