File类

File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

【案例 】创建一个文件

 import java.io.*;
class hello{
public static void main(String[] args) {
File f=new File("D:\\hello.txt");
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}

【案例2】File类的两个常量

 import java.io.*;
class hello{
public static void main(String[] args) {
System.out.println(File.separator);
System.out.println(File.pathSeparator);
}
}

此处多说几句:有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。

【案例3】File类中的常量改写案例1的代码:

 import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}

【案例4】删除一个文件(或者文件夹)

 import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
if(f.exists()){
f.delete();
}else{
System.out.println("文件不存在");
} }
}

【案例5】创建一个文件夹

 /**
* 创建一个文件夹
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello";
File f=new File(fileName);
f.mkdir();
}
}

【案例6】列出目录下的所有文件

 /**
* 使用list列出指定目录的全部文件
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
String[] str=f.list();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}

注意使用list返回的是String数组,。而且列出的不是完整路径,如果想列出完整路径的话,需要使用listFiles.它返回的是File的数组。

【案例7】列出指定目录的全部文件(包括隐藏文件):

 /**
* 使用listFiles列出指定目录的全部文件
* listFiles输出的是完整路径
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
File[] str=f.listFiles();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}

【案例8】判断一个指定的路径是否为目录

 /**
* 使用isDirectory判断一个指定的路径是否为目录
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
if(f.isDirectory()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}

【案例9】递归搜索指定目录的全部内容,包括文件和文件夹

 import java.io.File;

 public class Hello {
/**
* 列出指定目录的全部内容
*/
public static void main(String[] args) {
String fileName = "D:" + File.separator;
File f = new File(fileName);
print(f);
} private static void print(File f) {
if (f != null) {
if (f.isDirectory()) {
File[] fileArray = f.listFiles();
if (fileArray != null) {
for (int i = 0; i < fileArray.length; i++) {
print(fileArray[i]);
}
} else {
System.out.println(f);
}
}
}
} }

10.RandomAccessFile类
该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。该对象特点:
该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件路径;b.File对象。
该对象既可以对文件进行读操作,也能进行写操作,在进行对象实例化时可指定操作模式(r,rw)
注意:该对象在实例化时,如果要操作的文件不存在,会自动创建;如果文件存在,写数据未指定位置,会从头开始写,即覆盖原有的内容。可以用于多线程下载或多个线程同时写数据到文件。
【案例】使用RandomAccessFile写入文件

 /**
* 使用RandomAccessFile写入文件
* */
import java.io.*;
class hello{
public static void main(String[]args) throws IOException {
StringfileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
RandomAccessFile demo=newRandomAccessFile(f,"rw");
demo.writeBytes("asdsad");
demo.writeInt(12);
demo.writeBoolean(true);
demo.writeChar('A');
demo.writeFloat(1.21f);
demo.writeDouble(12.123);
demo.close();
}
Java IO流的高级概念
编码问题
【案例 】取得本地的默认编码
 /**
* 取得本地的默认编码
* */
publicclass CharSetDemo{
public static void main(String[] args){
System.out.println("系统默认编码为:"+ System.getProperty("file.encoding"));
}
}

【案例 】乱码的产生

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; /**
* 乱码的产生
* */
public class CharSetDemo2{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator + "hello.txt");
OutputStream out = new FileOutputStream(file);
byte[] bytes = "你好".getBytes("ISO8859-1");
out.write(bytes);
out.close();
}//输出结果为乱码,系统默认编码为GBK,而此处编码为ISO8859-1
对象的序列化</h2>
对象序列化就是把一个对象变为二进制数据流的一种方法。
一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。先让我们实现一个具有序列化能力的类吧:
【案例 】实现具有序列化能力的类
 import java.io.*;
/**
* 实现具有序列化能力的类
* */
public class SerializableDemo implements Serializable{
public SerializableDemo(){ }
publicSerializableDemo(String name, int age){
this.name=name;
this.age=age;
}
@Override
public String toString(){
return "姓名:"+name+" 年龄:"+age;
}
private String name;
private int age;
}

【案例 】序列化一个对象 – ObjectOutputStream

 import java.io.Serializable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 实现具有序列化能力的类
* */
public class Person implements Serializable{
public Person(){
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString(){
return "姓名:" +name + " 年龄:" +age;
}
private String name;
private int age;
}
/**
* 示范ObjectOutputStream
* */
public class ObjectOutputStreamDemo{
public static voidmain(String[] args) throws IOException{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(
file));
oos.writeObject(newPerson("rollen", 20));
oos.close();
}
}

【案例 】反序列化—ObjectInputStream

 import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream; /**
* ObjectInputStream示范
* */
public class ObjectInputStreamDemo{
public static voidmain(String[] args) throws Exception{
File file = new File("d:" +File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
}
注意:被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。
当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。
现在我们来演示一下序列化和反序列话:
【案例 】使用Externalizable来定制序列化和反序列化操作
 import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream; /**
* 序列化和反序列化的操作
* */
public class ExternalizableDemo{
public static voidmain(String[] args) throws Exception{
ser(); // 序列化
dser(); // 反序列话
} public static void ser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
file));
out.writeObject(newPerson("rollen", 20));
out.close();
} public static void dser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
} class Person implements Externalizable{
public Person(){ } public Person(String name,int age){
this.name = name;
this.age = age;
} @Override
public String toString(){
return "姓名:" +name + " 年龄:" +age;
} // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用
@Override
public voidwriteExternal(ObjectOutput out) throws IOException{
out.writeObject(this.name);
out.writeInt(age);
} // 复写这个方法,根据需要读取内容 反序列话的时候需要
@Override
public voidreadExternal(ObjectInput in) throws IOException,
ClassNotFoundException{
this.name = (String)in.readObject();
this.age =in.readInt();
} private String name;
private int age;
}
注意:Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,
当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:
【案例 】使用transient关键字定制序列化和反序列化操作
 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; /**
* 序列化和反序列化的操作
* */
public class serDemo{
public static voidmain(String[] args) throws Exception{
ser(); // 序列化
dser(); // 反序列话
} public static void ser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
file));
out.writeObject(newPerson1("rollen", 20));
out.close();
} public static void dser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
} class Person1 implements Serializable{
public Person1(){ } public Person1(Stringname, int age){
this.name = name;
this.age = age;
} @Override
public String toString(){
return "姓名:" +name + " 年龄:" +age;
} // 注意这里
private transient Stringname;
private int age;
}
【运行结果】:
姓名:null  年龄:20
【案例 】序列化一组对象

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; /**
* 序列化一组对象
* */
public class SerDemo1{
public static void main(String[] args) throws Exception{
Student[] stu = { new Student("hello", 20), new Student("world", 30),
new Student("rollen", 40) };
ser(stu);
Object[] obj = dser();
for(int i = 0; i < obj.length; ++i){
Student s = (Student) obj[i];
System.out.println(s);
}
} // 序列化
public static void ser(Object[] obj) throws Exception{
File file = new File("d:" + File.separator + "hello.txt");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
file));
out.writeObject(obj);
out.close();
} // 反序列化
public static Object[] dser() throws Exception{
File file = new File("d:" + File.separator + "hello.txt");
ObjectInputStream input = new ObjectInputStream(new FileInputStream(
file));
Object[] obj = (Object[]) input.readObject();
input.close();
return obj;
}
} class Student implements Serializable{
public Student(){ } public Student(String name, int age){
this.name = name;
this.age = age;
} @Override
public String toString(){
return "姓名: " + name + " 年龄:" + age;
} private String name;
private int age;
}

Java开发之File类的更多相关文章

  1. java中的File类

    File类 java中的File类其实和文件并没有多大关系,它更像一个对文件路径描述的类.它即可以代表某个路径下的特定文件,也可以用来表示该路径的下的所有文件,所以我们不要被它的表象所迷惑.对文件的真 ...

  2. java学习一目了然——File类文件处理

    java学习一目了然--File类文件处理 File类(java.io.File) 构造函数: File(String path) File(String parent,String child) F ...

  3. Java学习笔记——File类之文件管理和读写操作、下载图片

    Java学习笔记——File类之文件管理和读写操作.下载图片 File类的总结: 1.文件和文件夹的创建 2.文件的读取 3.文件的写入 4.文件的复制(字符流.字节流.处理流) 5.以图片地址下载图 ...

  4. Java基础之File类的使用

    Java基础之File类的使用 1.File类的构造方法和常用方法 2.对File中listFile(FileNameFilter name)学习 3.与File文件类相关的实现 File类的构造方法 ...

  5. Java—IO流 File类的常用API

    File类 1.只用于表示文件(目录)的信息(名称.大小等),不能用于文件内容的访问. package cn.test; import java.io.File; import java.io.IOE ...

  6. java io包File类

    1.java io包File类, Java.io.File(File用于管理文件或目录: 所属套件:java.io)1)File对象,你只需在代码层次创建File对象,而不必关心计算机上真正是否存在对 ...

  7. Java学习:File类

    Java学习:File类 File类的概述 重点:记住这三个单词 绝对路径和相对路径 File类的构造方法 File类判断功能的方法 File类创建删除功能的方法 File类获取(文件夹)目录和文件夹 ...

  8. java IO之 File类+字节流 (输入输出 缓冲流 异常处理)

    1. File类

  9. Java开发之JSP指令

    一.page指令 page指令是最常用的指令,用来说明JSP页面的属性等.JSP指令的多个属性可以写在一个page指令里,也可以写在多个指令里.但需要注意的是,无论在哪个page指令里的属性,任何pa ...

随机推荐

  1. DTCMS展示一级栏目并展示各自栏目下的二级栏目

    c#代码中 <!--C#代码--> <%csharp%> string parent_id=DTRequest.GetQueryString("parent_id&q ...

  2. 为什么Facebook要将视频从Flash全面迁移到HTML5?

    英文原文:Why we chose to move to HTML5 video 编者按:Facebook 前端高级工程师 Daniel Baulig 解释了 Facebook 为什么要将视频全面迁移 ...

  3. Java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

    如果你更新了ADT的新版本,而工程文件中使用了其他的jar包,也可能会出现"java.lang.RuntimeException: Unable to instantiate activit ...

  4. C# login with cookie and fiddler2

    http://blog.codeblack.nl/post/HttpWebRequest-HttpWebResponse-and-cookies.aspx CookieContainer cookie ...

  5. Linux下Mysql数据库备份

    今天一同事的电脑无缘无故坏了,找了IT部门检测说是硬盘坏了,数据无法恢复.好悲剧.自己博客也写了好久不容易,要是突然间数据丢了那怎么办!于是写了个数据库自动备份脚本,并创建任务计划,实现每天22:30 ...

  6. 【BZOJ 1491】 [NOI2007]社交网络

    Description Input Output 输出文件包括n 行,每行一个实数,精确到小数点后3 位.第i 行的实数表 示结点i 在社交网络中的重要程度. Sample Input 4 4 1 2 ...

  7. TOPAPI 消息通知机制

    接收用户订阅消息 public class UserSubMain { public static void main(String[] args ) throws ApiException { St ...

  8. mysql-community-server 5.7.16 设置密码

    那是由于mysql-community-server 5.7的密码是一个默认的随机密码,这个初始密码,mysql又不告诉你,我们需要重设这个密码. service mysqld stop mysqld ...

  9. C# Windows - RadioButton&CheckBox

    RadioButton和CheckBox控件与Button控件有相同的基类,但它们的外观和用法大不相同. RadioButton显示为一个标签,左边是一个圆点,该点可以是选中或未选中.用在给用户提供两 ...

  10. windows server 2008 r2电脑历史操作记录

    1.看计算机哪天运行过.    在系统盘下的Windows\Tasks文件夹下找到文件SCHEDLGU.TXT. 2.看你最近打开过什么文件(非程序)或者文件夹    开始-->运行--> ...