五、File类,内存流和其他功能IO流的使用
【1】File类总结
public static void testFileFuns() throws IOException{
File f1 = new File("d:/java/test.txt");
File f2 = new File("d:/java/","test.txt");
File f3 = new File("d:/a/b/c");
File f4 = new File("d:/java/test2.txt");
System.out.println("f1"+f1);
System.out.println("f2"+f2);
//①文件创建
boolean boo = f1.createNewFile();//有则不创建
System.out.println("f1create:"+boo);
boo = f3.mkdir();
boo = f3.mkdirs();//创建所有目录
//②文件删除
boo = f1.delete();
System.out.println("f1delete:"+boo);
f1.deleteOnExit();//程序结束时执行删除动作
//③文件判断
boo = f1.canExecute();
boo = f1.canRead();
boo = f1.canWrite();
boo = f1.exists();//文件是否存在
//>>※判断是目录还是文件的时候必须先判断文件是否存在
boo = f1.isDirectory();
boo = f1.isFile();
boo = f1.isHidden();
boo = f1.isAbsolute();
//④文件信息
String name = f1.getName();
System.out.println(name);
String path = f1.getPath();
System.out.println(path);
String parent = f1.getParent();//返回绝对路径中的父目录,相对路径返回null
System.out.println(parent);
String absolutePath = f1.getAbsolutePath();
System.out.println(absolutePath);
Long lastMtime = f1.lastModified();
System.out.println(lastMtime);
Long size = f1.length();
System.out.println(size);
File[] roots = File.listRoots();//列出系统所有盘符
System.out.println(Arrays.toString(roots));
File[] fs = new File("c:/").listFiles();
System.out.println(Arrays.toString(fs));
File[] javafs = new File("d:/java/").listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".java");
}
});
System.out.println(Arrays.toString(javafs));
//⑤文件重命名
f1.renameTo(f2);
}
★遍历文件
/**
* tree dir
* @param dir
* @param prefix
*/
public static void tree(File dir,String prefix){
File[] fs = dir.listFiles();
for (int i = 0;i<fs.length;i++) {
File file = fs[i];
if(file.isDirectory()){
System.out.println(prefix+((i+1)!=fs.length?"├─":"└─")+file.getName());
tree(file, prefix+ "│ ");
}else{
System.err.println(prefix+((i+1)!=fs.length?"├─":"└─")+file.getName());
}
}
}
【2】Properties
☆与IO结合的集合
Properties prop = new Properties();
prop.setProperty("color", "red");
//打印到控制台
prop.list(System.out);
//保存至属性文件
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("d:/java/property.ini"));
prop.store(fos, "copyright:lfd");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(fos!=null){
fos.close();
}
}
【3】打印流PrintStream/Writer
☆为其他流添加n多功能,可以直接原样打印各种数据类型数据
☆PrintStream,能直接操作文件,字节输出流,
☆PrintWriter 增加接受字符输出流
PrintWriter pw = new PrintWriter(new File("d:/java/pw.txt"), "utf-8");
pw.println("联通哈哈");
pw.println(false);
pw.println(123456);
pw.println(12.34);
pw.close();
pw = new PrintWriter(System.out,true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String ln = null;
while((ln=br.readLine())!=null){
if("over".equals(ln)){
break;
}
pw.println("-->"+ln);
}
pw.close();
br.close();
【4】合并流:SequenceInputStream
☆对多个输入流进行合并
List<InputStream> list = new ArrayList<InputStream>();
list.add(new FileInputStream("d:/java/1.txt"));
list.add(new FileInputStream("d:/java/2.txt"));
list.add(new FileInputStream("d:/java/3.txt"));
final Iterator<InputStream> iis = list.iterator();
Enumeration<InputStream> eis = new Enumeration<InputStream>() {
@Override
public InputStream nextElement() {
return iis.next();
}
@Override
public boolean hasMoreElements() {
return iis.hasNext();
}
};
SequenceInputStream sis = new SequenceInputStream(eis);
FileOutputStream fos = new FileOutputStream("d:/java/coll.txt");
byte[] buff = new byte[512];
int len = 0;
while((len = sis.read(buff))!=-1){
fos.write(buff,0, len);
}
fos.close();
sis.close();
【5】对象流:ObjectInput/OutputStream
☆保存的对象需要实现序列化接口
☆static字段是无法保存的
☆transient修饰的字段保存时忽略
package com.lfd.io.learn;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class L12ObjectStream {
public static void main(String[] args) throws Exception {
// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/java/persion.txt"));
// Persion p = new Persion("张三",100);
// Persion.num = 1000;
// oos.writeObject(p);
// oos.close();
// System.out.println(p.getName());
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/java/persion.txt"));
Persion p = (Persion)ois.readObject();
ois.close();
System.out.println(p);//输出:name:null>age:100>num:null
}
}
class Persion implements Serializable{
private static final long serialVersionUID = 1L;
private transient String name;
public static Integer num;
private int age;
public Persion(String name,int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "name:"+name+">age:"+age+">num:"+num;
}
}
【6】管道流:PipedInput/OutputStream
☆多线程使用,输入输出链接使用,直到写入到数据后,输出流提供给输输入流数据,否则输入流一直处于等待状态。
package com.lfd.io.learn;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class L13PipedStream {
public static void main(String[] args) throws IOException {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos);
new Thread(new Reader(pis)).start();
new Thread(new Writer(pos)).start();
}
}
/**
*管道输入流线程
*/
class Reader implements Runnable{
PipedInputStream pis;
public Reader(PipedInputStream pis) {
this.pis = pis;
}
@Override
public void run() {
byte[] buff = new byte[1024];
try {
int len = pis.read(buff);
System.out.println(new String(buff,0,len));
pis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 管道输出流线程
*/
class Writer implements Runnable{
PipedOutputStream pos;
public Writer(PipedOutputStream pos) {
this.pos = pos;
}
@Override
public void run() {
try {
Thread.sleep(1000);
pos.write("hello piped!".getBytes());
pos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
【7】RandomAccessFile
☆非IO体系子类,但可读可写;内部封装大大的字节数组,可通过指针操作
☆getFilePointer获取指针位置,seek改变指针位置,Random->可以在文件任何地方读写
☆内部封装字节输入输出流
☆只能操作文件,文件不存在则创建,存在,不会覆盖
RandomAccessFile raf = new RandomAccessFile("d:/java/test.txt", "rw");
raf.writeByte(100);
raf.writeInt(10);
raf.writeBoolean(true);
raf.writeInt(20);
raf.writeDouble(2.12);
raf.seek(0);//指针指向开头除
byte b = raf.readByte();
System.out.println(b);
raf.skipBytes(4);//跳过4个字节
boolean boo = raf.readBoolean();
System.out.println(boo);
raf.seek(1);
int i = raf.readInt();
System.out.println(i);
raf.close();
【8】基本数据类型DataStream
DataOutputStream dos = new DataOutputStream(new FileOutputStream("d:/java/test.txt"));
DataInputStream dis = new DataInputStream(new FileInputStream("d:/java/test.txt"));
dos.writeInt(100);
dos.writeDouble(1.01);
dos.writeBoolean(true);
dos.writeUTF("hello!");//此UTF编码为UTF-8修改版,只能对应的dis读取
dos.close();
int i = dis.readInt();
double d = dis.readDouble();
boolean b = dis.readBoolean();
String s = dis.readUTF();
System.out.println(i);
System.out.println(d);
System.out.println(b);
System.out.println(s);
dis.close();
【9】内存流:ByteArrayStream,CharArrayReader/Writer,StringReader/Writer
☆由于没有打开资源,所以不用close
//字节数组IO流
ByteArrayInputStream bais = new ByteArrayInputStream("ABCDE".getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int data = 0;
while((data=bais.read())!=-1){
baos.write(data);
}
FileOutputStream fos = new FileOutputStream("d:/java/test2.txt");
baos.writeTo(fos);//写入到输出流中
fos.close();
System.out.println(baos.toString());
//字符数组IO流
CharArrayReader car = new CharArrayReader("AAAAA".toCharArray());
CharArrayWriter caw = new CharArrayWriter();
data = 0;
while((data=car.read())!=-1){
caw.write(data);
}
System.out.println(caw.toString());
//String
StringReader sr = new StringReader("BBBBB");
StringWriter sw = new StringWriter();
data = 0;
while((data=sr.read())!=-1){
sw.write(data);
}
sw.append("END");
System.out.println(sw.toString());
【10】字符编码
☆ASCII(美国编码,7位)
☆ISO8859-1(欧洲,一个字节)
☆GB2312,GBK(中国,二个字节,兼容ASCII)
☆Unicode(国际标准,所有字符均二个字节)
☆UTF-8(Unicode的实现之一,最多3个字节表示一个字符)
☆【gbk等编码->ISO8859-1解码->ISO8859-1编码->gbk等解码】√
【gbk等编码->UTF-8解码->UTF-8编码->gbk等解码】X(unicode编码无法识别的字符用占位符表示U+FFFD,造成不可逆)
【11】练习:五个学生,三门成绩,键盘输入(zhangsan,30,40,60,计算出总成绩),成绩高低顺序存放stud.txt中
<pre name="code" class="java">package com.lfd.io.learn;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class L17IOTrain {
public static void main(String[] args) {
try {
Comparator<Student> comp = Collections.reverseOrder();//比较反转
StudentInfoTools.write2File(StudentInfoTools.getStudents(comp));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class StudentInfoTools{
public static Set<Student> getStudents() throws IOException{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> comp) throws IOException{
Set<Student> ss = null;
if(comp == null){
ss = new TreeSet<Student>();
}else{
ss = new TreeSet<Student>(comp);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String ln = null;
try {
while(!"over".equals(ln = br.readLine())){
String[] infos = ln.split(",");
Student st = new Student(infos[0],
Integer.parseInt(infos[1]),
Integer.parseInt(infos[2]),
Integer.parseInt(infos[3]));
ss.add(st);
}
} catch (IOException e) {
throw e;
}finally{
try {
if(br!=null)
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return ss;
}
public static void write2File(Set<Student> ss) throws IOException{
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("d:/java/stud.txt"));
for (Student st : ss) {
bw.write(st.toString()+"\t");
bw.write(st.getSum()+"");
bw.newLine();
bw.flush();
}
} catch (IOException e) {
throw e;
}finally{
if(bw!=null)bw.close();
}
}
}
class Student implements Comparable<Student> {
private String name;
private int math;
private int cn;
private int en;
private int sum;
public Student(String name, int math, int cn, int en) {
this.name = name;
this.math = math;
this.cn = cn;
this.en = en;
this.sum = math + cn + en;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getCn() {
return cn;
}
public void setCn(int cn) {
this.cn = cn;
}
public int getEn() {
return en;
}
public void setEn(int en) {
this.en = en;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
@Override
public int compareTo(Student o) {
return o.sum == this.sum ? 0 : (this.sum < o.sum ? -1 : 1);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student other = (Student) obj;
if (this.name.equals(other.name)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return MessageFormat.format("Student[{0},{1},{2},{3}]", name,math,cn,en);
}
}