一、File类

File(File parent, String child);

File(Stirng filename);

--------------------------------------------------------

//使用相对路径创建文件和目录

package pack02;





import java.io.File;

import java.io.IOException;





public class FileTest {

public static void main(String[] args) throws IOException{

File file = new File("1.txt");

//file.createNewFile();

file.mkdir();

}

}

--------------------------------------------------

/**

 * 使用绝对路径创建文件或目录

 */

package pack02;





import java.io.File;

import java.io.IOException;





public class FileTest {

public static void main(String[] args) throws IOException{

File file = new File("E:\\javaTest\\lesson\\1.txt");

file.createNewFile();

}

}

------------------------------------------------------------

separator 用string类型表示分割符

separatorChar 用char类型表示分隔符

------------------------------------------------------------

/**

 * 不依赖系统平台的绝对路径

 */

package pack02;





import java.io.File;

import java.io.IOException;





public class FileTest {

public static void main(String[] args) throws IOException{

//可以直接用separator表示当前根目录

File fDir = new File(File.separator);

//E:\Javalesson\lesson7\1.txt

String strFile = "JavaLesson" + File.separator + "Lesson7"

+File.separator+"1.txt";

File f = new File(fDir, strFile);

f.createNewFile();

}

}

----------------------------------------------------------------

File f = new File(fDir, strFile);

f.createNewFile();

f.delete()   //删除文件

f.deleteOnExit()  //当程序终止的时候删除文件

-----------------------------------------------------------------

/**

 * 创建临时文件并在程序结束时删除该文件

 * 创建的临时文件在:

 * 我的电脑-->环境变量-->Temp(指定的目录)

 */

package pack02;





import java.io.File;

import java.io.IOException;





public class FileTest {

public static void main(String[] args) throws IOException{

for(int i=0;i<5;i++){

File f = File.createTempFile("winsun","temp");

f.deleteOnExit();

}

// try {

// Thread.sleep(3000);

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

}

}

------------------------------------------------------------------

list()方法:返回这个目录下的所有文件名和子目录名

import java.io.File;

import java.io.FilenameFilter;

import java.io.IOException;





public class FileTest {

public static void main(String[] args) throws IOException{

String strFile = "E:"+File.separator+"A"+File.separator+"B"+File.separator;

File f = new File(strFile);

String[] names = f.list(new FilenameFilter(){

public boolean accept(File dir, String name) {

//System.out.println(dir);

return name.indexOf(".java") != -1;

}

});

for(String s:names){

System.out.println(s);

}

}

}

-------------------------------------------------------------------------

Decorater 装饰设计模式

节点流:从特定的地方读写的流。

过滤流:使用节点流作为输入或输出。

InputStream

abstract int read(); 读一个字节数据, 返回-1表示到了流的末尾

int read(byte[] b);   将数据读入字节数组 ,最后一次返回实际读取的字节数

int read(byte[] b, int off,  int len);  从指定位置读取, 最后一次返回实际读取的字节数

--------------------------------------------------------------------------

import java.io.*;

//将字符串写入文件

public class FileTest {

public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("1.txt");

out.write("http://www.baidu.com".getBytes());

out.close();

}

}

--------------------------------------------------------------------------

import java.io.*;

//将字符串从文件中读出

public class FileTest {

public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("1.txt");

out.write("http://www.baidu.com".getBytes());

out.close();

FileInputStream in = new FileInputStream("1.txt");

byte[] b = new byte[1024];

int len = in.read(b);

System.out.println(new String(b,0,len));

in.close();

}

}

--------------------------------------------------------------------------

import java.io.*;

//使用缓冲流写入数据到文件

public class FileTest {

public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("2.txt");

BufferedOutputStream bufOut = new BufferedOutputStream(out);

bufOut.write("http:www.baidu.com".getBytes());

bufOut.close(); //注意关闭的时候只需要关闭尾端的流

}

}

------------------------------------------------------------------------------

import java.io.*;

//使用缓冲流读出文件中数据

public class FileTest {

public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("2.txt");

BufferedOutputStream bufOut = new BufferedOutputStream(out);

bufOut.write("http:www.baidu.com".getBytes());

bufOut.close();

FileInputStream in = new FileInputStream("2.txt");

BufferedInputStream bufIn = new BufferedInputStream(in);

byte[] b = new byte[1024];

int len = bufIn.read(b);

System.out.println(new String(b,0,len));

bufIn.close();

}

}

-------------------------------------------------------------------------------

读取java中基本数据类型的类 DataInputStream()  DataOutputStream();

import java.io.*;

//使用Data过滤流读写

public class FileTest {

public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("2.txt");

BufferedOutputStream bufOut = new BufferedOutputStream(out);

DataOutputStream dataOut = new DataOutputStream(bufOut);

byte b = 3;

int i = 13;

char c = 'a';

float f = 12.3f;

dataOut.writeByte(b);

dataOut.writeInt(i);

dataOut.writeChar(c);

dataOut.writeFloat(f);

dataOut.close();

FileInputStream in = new FileInputStream("2.txt");

BufferedInputStream bufIn = new BufferedInputStream(in);

DataInputStream dataIn = new DataInputStream(bufIn);

byte b1 = dataIn.readByte();


int i1 = dataIn.readInt();

char c1 = dataIn.readChar();

float f1 = dataIn.readFloat();

System.out.println(b1);   //注意读和写的顺序必须一样,才能读对

System.out.println(i1);

System.out.println(c1);

System.out.println(f1);

dataIn.close();

}

}

------------------------------------------------------------------------

管道流  PipedInputStream  PipedOutputStream   他们总是成对出现的(注意这不是过滤流)

import java.io.*;

//使用Data过滤流读写

public class FileTest {



public static void main(String[] args) throws IOException{

PipedOutputStream pipOut = new PipedOutputStream();

PipedInputStream pipIn = new PipedInputStream();

pipOut.connect(pipIn);

new Produce(pipOut).start();

new Consumer(pipIn).start();

}



}

class Produce extends Thread{

private PipedOutputStream pipOut;

public Produce(PipedOutputStream pipOut){

this.pipOut = pipOut;

}

public void run(){

try {

pipOut.write("hello wellcome in file".getBytes());

pipOut.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

class Consumer extends Thread{

private PipedInputStream pipIn;

public Consumer(PipedInputStream pipIn){

this.pipIn = pipIn;

}

public void run(){

byte[] b = new byte[1024];

try {

int len = pipIn.read(b);

System.out.println(new String(b, 0, len));

} catch (IOException e) {

e.printStackTrace();

}

}

}

------------------------------------------------------------------------

上面是字节流,下面是字符流

OutputStreamWriter() 从字节流到字符流转换

InputStreamRead()  从字符流到字节流转换

通常使用Buffered流进行读写

-------------------------------------------------------------------------

import java.io.*;

//使用字符流读写数据

public class FileTest {



public static void main(String[] args) throws IOException{

FileOutputStream out = new FileOutputStream("3.txt");

OutputStreamWriter w = new OutputStreamWriter(out);

BufferedWriter bufW = new BufferedWriter(w);

bufW.write("http://www.baidu.com");

bufW.close();



FileInputStream in = new FileInputStream("3.txt");

InputStreamReader r = new InputStreamReader(in);

BufferedReader bufI = new BufferedReader(r);

String str = bufI.readLine();  //可以读一行

System.out.println(str);

bufI.close();

}

}

----------------------------------------------------------------------------

import java.io.*;

//从控制台输入并打印到控制台

public class FileTest {



public static void main(String[] args) throws IOException{

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader bufIn = new BufferedReader(in);

String str;

while((str=bufIn.readLine()) != null){

System.out.println(str);

}

bufIn.close();

}

}

-----------------------------------------------------------------------------

ASCII :美国信息互换标准编码  是用一个字节来表示字符

GB2312:中华人民共和国汉子信息交换用码   一个中文用两个字节表示

GBK  :k是“扩展”   兼容GB2312,繁体,许多符号,不常用汉字编码

ISO-8859-1 :西方国家使用的字符编码,是一种单字节字符集,而英文只使用了小于128的部分

Unicode :通用的字符集,对所有语言的文字进行了统一的编码,每一个字符用两个字节来表示

但是对英文字符(一个字符用两个字节表示,浪费)

UTF-8 :通用字符集,英文用一个字节表示,是一种用适合长度字节表示不同字符。

-------------------------------------------------------------------------------

import java.io.*;

import java.nio.*;

import java.nio.charset.Charset;

import java.util.*;

//打印java中能够使用的所有的字符编码

public class FileTest {



public static void main(String[] args) throws IOException{

Map m = Charset.availableCharsets();

Set s = m.keySet();

Iterator i = s.iterator();

while(i.hasNext()){

System.out.println(i.next());

}

}

}

---------------------------------------------------------------------------------------

解码和编码

本地码----->其他编码(编码)

---------------------------------------------------------------------------------

/**

 * 从屏幕上读取虚拟机信息

 */

package pack02;





import java.util.Properties;





public class FileTest {

public static void main(String[] args){

Properties pps = System.getProperties();

pps.list(System.out);

}

}

-----------------------------------------------------------------------------------

/**

 * 改变虚拟机默认字符集,后从控制台读入解码,再编码为字符串输出

 */

package pack02;





import java.io.IOException;

import java.nio.Buffer;

import java.util.Properties;





import com.sun.jndi.url.iiopname.iiopnameURLContextFactory;





public class FileTest {

public static void main(String[] args) throws IOException{

Properties pps = System.getProperties();

pps.put("file.encoding", "ISO-8859-1");

int data;

byte[] b = new byte[1024];

int len = 0;

while((data=System.in.read()) != 'q'){

b[len] = (byte)data;

len ++;

}

String str = new String(b, 0, len);

System.out.println(str);

}

}

-----------------------------------------------------------------------------------

RandomAccessFile类





package pack02;





import java.io.IOException;

import java.io.RandomAccessFile;





class RandomFileTest{

public static void main(String[] args) throws Exception{

Student s1 = new Student(1,"zs",67);

Student s2 = new Student(2,"ls",89);

Student s3 = new Student(3,"wu",98);

RandomAccessFile raf = new RandomAccessFile("Student.txt","rw");

s1.writeStudent(raf);

s2.writeStudent(raf);

s3.writeStudent(raf);

Student s = new Student();

raf.seek(0);  //指向开始

//length()获取文件长度,  getFilePointer()一个指针

for(long i=0;i<raf.length();raf.getFilePointer()){

s.readStudent(raf);

System.out.println(s.name);

System.out.println(s.num);

System.out.println(s.score);

}

raf.close(); //关闭流

}

}

class Student{

int num;

String name;

double score;

public Student(){



}

public Student(int num,String name,double score){

this.num = num;

this.name = name;

this.score = score;

}

public void writeStudent(RandomAccessFile raf)throws IOException{

raf.writeInt(num);

raf.writeUTF(name); 

raf.writeDouble(score);

}

public void readStudent(RandomAccessFile raf) throws IOException{

num = raf.readInt();

name = raf.readUTF();

score = raf.readDouble();

}

}

----------------------------------------------------------------------------

对象序列化

将对象转换为字节流保存起来,并在日后还原这个对象,这种机制叫做对象序列

将一个对象保存到永久存储设备上称为持续性。

一个对象要想能够实现序列化,必须实现Serializable接口或Externalizable接口。

1.Serializable是一个空接口(没有方法)

2.Externalizable继承自Serializable接口

-----------------------------------------------------------------------------

package pack02;





import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;





public class ObjectSerialTest {

public static void main(String[] args) throws IOException, ClassNotFoundException{

Employee e1 = new Employee("zhangsan",25,3000.5);

Employee e2 = new Employee("lisi",24,6000.5);

Employee e3 = new Employee("wangwu",45,60660.5);

FileOutputStream fos = new FileOutputStream("employee.txt");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(e1);

oos.writeObject(e2);

oos.writeObject(e3);


oos.close();

FileInputStream fis = new FileInputStream("employee.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

Employee e;

for(int i=0;i<3;i++){

e =(Employee)ois.readObject();

System.out.println(e.name);

System.out.println(e.salary);

System.out.println(e.age);

}

ois.close();

}

}

class Employee implements Serializable{

String name;

int age;

double salary;

public Employee() {

super();

}

public Employee(String name, int age, double salary) {

super();

this.name = name;

this.age = age;

this.salary = salary;

}





}

-----------------------------------------------------------------------------

当一个对象被序列化时,只保存对象的非静态成员变量,不能保存任何的成员方法和静态的成员变量。

如果一个对象的成员变量是一个对象,那么这个对象的数据也会被保存。

如果一个可序列化的对象包含对某个不可序列化的对象的引用,那么整个序列化操作将会失败,

并且会抛出一个NotSerializableException.我们可以将这个引用标记为transient,那么对象任然可以序列化。

------------------------------------------------------------------------------

package pack02;





import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;





public class ObjectSerialTest {

public static void main(String[] args) throws IOException, ClassNotFoundException{

Employee e1 = new Employee("zhangsan",25,3000.5);

Employee e2 = new Employee("lisi",24,6000.5);

Employee e3 = new Employee("wangwu",45,60660.5);

FileOutputStream fos = new FileOutputStream("employee.txt");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(e1);

oos.writeObject(e2);

oos.writeObject(e3);


oos.close();

FileInputStream fis = new FileInputStream("employee.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

Employee e;

for(int i=0;i<3;i++){

e =(Employee)ois.readObject();

System.out.println(e.name);

System.out.println(e.salary);

System.out.println(e.age);

System.out.println(e.thread); //可以被序列化

}

ois.close();

}

}

class Employee implements Serializable{

String name;

int age;

double salary;

//Thread thread  = new Thread(); //不可序列化的对象

//加上transient后可以被序列化

//可以序列化的不想被序列化也可以在前面加上transient

transient Thread thread = new Thread();

public Employee() {

super();

}

public Employee(String name, int age, double salary) {

super();

this.name = name;

this.age = age;

this.salary = salary;

}

}

-----------------------------------------------------------------------------------

重写 readObject()和writeObject()方法

//这两个方法是一个特例,声明为private后在外面能被调用

private void  writeObject(java.io.ObjectOutputStream oos) throws IOException{

oos.writeInt(age);

oos.writeUTF(name);

System.out.println("wirte object);

}

private void readObject(java.io.ObjectInputStream ois) throws IOException{

age = ois.readInt();

name = ois.readUTF();

System.out.println("read object");

}

java学习笔记(7)——I/O流的更多相关文章

  1. Java学习笔记之I/O流(读取压缩文件以及压缩文件)

    1.读取压缩文件:ZipInputStream 借助ZipFile类的getInputStream方法得到压缩文件的指定项的内容,然后传递给InputStreamReader类的构造方法,返回给Buf ...

  2. Java学习笔记43(打印流、IO流工具类简单介绍)

    打印流: 有两个类:PrintStream,PrintWriter类,两个类的方法一致,区别在于构造器 PrintStream:构造方法:接收File类型,接收字符串文件名,接收字节输出流(Outpu ...

  3. Java学习笔记42(序列化流)

    对象中的数据,以流的形式,写入到文件中保存 过程称为写出对象,对象的序列化 ObjectOutputStream将对象写到文件中,实现序列化 在文件中,以流的形式,将对象读取出来, 读取对象,对象的反 ...

  4. Java学习笔记40(缓冲流)

    缓冲流: 在读写文件的各种流中,最令人烦恼的就是效率问题, 而缓冲流的目的就是提高读写效率 字节输出缓冲流: package demo; import java.io.BufferedOutputSt ...

  5. Java学习笔记39(转换流)

    转换流:字符流和字节流之间的桥梁 用于处理程序的编码问题 OutputStreamWriter类:字符转字节流 写文本文件: package demo; import java.io.FileOutp ...

  6. Java学习笔记38(字符流)

    字符输出流:Writer类:使用时候需要它的子类 局限性:只能写文本文件,无法写其他文件 方法: package demo; import java.io.FileWriter; import jav ...

  7. Java学习笔记(7)---流(Stream),文件(File)

    1.Stream流 a.定义: Java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io 包中的流支持很多种格式,比如:基本类型.对象.本地化字符集 ...

  8. java学习笔记16--I/O流和文件

    本文地址:http://www.cnblogs.com/archimedes/p/java-study-note16.html,转载请注明源地址. IO(Input  Output)流 IO流用来处理 ...

  9. 《Java学习笔记(第8版)》学习指导

    <Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...

  10. 20145330第十周《Java学习笔记》

    20145330第十周<Java学习笔记> 网络编程 网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定的数据,这个就 ...

随机推荐

  1. Ansible 管理服务和软件

    [root@Ansible ~]# ansible RAC -m yum -a 'name=iscsi-initiator-utils state=installed' RAC_Node1 | suc ...

  2. watchdog的正确使用方法

    关于watchdog应该有过单片机学习经历的人.都比較熟悉.但watchdog的正确使用方法,恐怕大家假设没有经历过实际产品的开发不会有深入的理解. 瑞萨RL78系列的单片机自身带有watchdog, ...

  3. sqlplus中怎么将你全部的操作和结果记录保存到你指定的文件里

    [在sqlplus的操作中,非常多时候我们都想把自己的写的sql语句和改动日志或者结果信息做记录] [首先]肯定要正常连接到oralce数据库. [然后] 你用你指定的用户登录到oralce数据库之后 ...

  4. [React] Setup 'beforeunload' listener

    In this lesson we'll show how to take a beforeUnload call and convert it to a declarative React Comp ...

  5. JAVA Concurrent包 中的并发集合类

    我们平时写程序需要经常用到集合类,比如ArrayList.HashMap等,但是这些集合不能够实现并发运行机制,这样在服务器上运行时就会非常的消耗资源和浪费时间,并且对这些集合进行迭代的过程中不能进行 ...

  6. 【u118】日志分析

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] M 海运公司最近要对旗下仓库的货物进出情况进行统计.目前他们所拥有的唯一记录就是一个记录集装箱进出情况 ...

  7. [Ramda] Handle Branching Logic with Ramda's Conditional Functions

    When you want to build your logic with small, composable functions you need a functional way to hand ...

  8. Best Practices for QML and Qt Quick

    Despite all of the benefits that QML and Qt Quick offer, they can be challenging in certain situatio ...

  9. USB 3.0规范中译本 第1章 引言

    本文为CoryXie原创译文,转载及有任何问题请联系cory.xie#gmail.com. 1.1 动机(Motivation) Universal Serial Bus (USB) 的原始动机来自于 ...

  10. 【u003】计算概率

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 小明有n个长度不一的小木棍,这些木棍的长度都是正整数.小明的父亲想和小明做一个游戏.他规定一个整数长度 ...