java学习笔记(7)——I/O流
一、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流的更多相关文章
- Java学习笔记之I/O流(读取压缩文件以及压缩文件)
1.读取压缩文件:ZipInputStream 借助ZipFile类的getInputStream方法得到压缩文件的指定项的内容,然后传递给InputStreamReader类的构造方法,返回给Buf ...
- Java学习笔记43(打印流、IO流工具类简单介绍)
打印流: 有两个类:PrintStream,PrintWriter类,两个类的方法一致,区别在于构造器 PrintStream:构造方法:接收File类型,接收字符串文件名,接收字节输出流(Outpu ...
- Java学习笔记42(序列化流)
对象中的数据,以流的形式,写入到文件中保存 过程称为写出对象,对象的序列化 ObjectOutputStream将对象写到文件中,实现序列化 在文件中,以流的形式,将对象读取出来, 读取对象,对象的反 ...
- Java学习笔记40(缓冲流)
缓冲流: 在读写文件的各种流中,最令人烦恼的就是效率问题, 而缓冲流的目的就是提高读写效率 字节输出缓冲流: package demo; import java.io.BufferedOutputSt ...
- Java学习笔记39(转换流)
转换流:字符流和字节流之间的桥梁 用于处理程序的编码问题 OutputStreamWriter类:字符转字节流 写文本文件: package demo; import java.io.FileOutp ...
- Java学习笔记38(字符流)
字符输出流:Writer类:使用时候需要它的子类 局限性:只能写文本文件,无法写其他文件 方法: package demo; import java.io.FileWriter; import jav ...
- Java学习笔记(7)---流(Stream),文件(File)
1.Stream流 a.定义: Java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io 包中的流支持很多种格式,比如:基本类型.对象.本地化字符集 ...
- java学习笔记16--I/O流和文件
本文地址:http://www.cnblogs.com/archimedes/p/java-study-note16.html,转载请注明源地址. IO(Input Output)流 IO流用来处理 ...
- 《Java学习笔记(第8版)》学习指导
<Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...
- 20145330第十周《Java学习笔记》
20145330第十周<Java学习笔记> 网络编程 网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定的数据,这个就 ...
随机推荐
- Hibernate与代理模式
代理模式:当须要调用某个对象的时候.不须要关心拿到的是不是一定是这个对象,它须要的是,我拿到的这个对象能够完毕我想要让它完毕的任务就可以,也就是说.这时调用方能够拿到一个代理的一个对象,这个对象能够调 ...
- 【u106】3D模型
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 一座城市建立在规则的n×m网格上,并且网格均由1×1正方形构成.在每个网格上都可以有一个建筑,建筑由若 ...
- C++设计模式实现--备忘录(Memento)模式
一. 备忘录模式 定义:在不破坏封装性的前提下,捕获一个对象的内部状态.并在该对象之外保存这个状态. 这样以后就可将该对象恢复到原先保存的状态. 结构图: 使用范围: Memento 模式比較适用于功 ...
- [Angular2 Router] Guard: CanLoad
'canLoad' guard can decide whether a lazy load module can be loaded or not. @Injectable() export cla ...
- 日期和时间的格式化定义(ISO C89)
格式化定义本质上控制的是占位. 日期 %Y:4位数的年份: %y:2位数的年份: %m:2位数的月份(1-12) %d:2位数的日(01-31) 时间 %H:24小时制(0-23) %I:12小时制( ...
- Swift基础1.1——基本的语法—变量和常量
前些日子.第一届Swift开发人员大会开了之后.身边非常多搞OC的朋友就按捺不住了. 都认为是时候学一下Swift了,毕竟Swift已是趋势. 也是应他们再三要求,让我整理一下Swift的学习心得.今 ...
- HPE Comware Lab - Simulator
http://h20565.www2.hpe.com/hpsc/swd/public/readIndex?sp4ts.oid=7107838&ac.admitted=1405352934644 ...
- HBase总结(十一)hbase Java API 介绍及使用演示样例
几个相关类与HBase数据模型之间的相应关系 java类 HBase数据模型 HBaseAdmin 数据库(DataBase) HBaseConfiguration HTable 表(Table) H ...
- [Javascript] Javascript 'in' opreator
If you want to check whether a key is inside an Object or Array, you can use 'in': Object: const obj ...
- 主从同步设置的重要参数log_slave_updates
说明:最近部署了mysql的集群环境,详细如下M01和M02为主主复制,M01和R01为主从复制:在测试的过程中发现了以下问题: 1.M01和M02的主主复制是没有问题的(从M01写入数据能同步到M0 ...