写文本文件

写入文本文件

import java.io.*;

public class FileWriterTester {
	//main中声明抛出IO异常
    public static void main(String[] args) throws IOException {
        String fileName = "Hello.txt";//文件名
        //创建文本文件的时候要构造一个FileWriter对象,文件名作为参数(相对路径名或绝对路径)
        FileWriter writer = new FileWriter(fileName);
        writer.write("hello!\n");//\n作为换行符
        writer.write("this is my first text file,\n");
        writer.write("You can see how this is done.\n");
        writer.write("输入一行中文也可以\n");
        writer.close();
    }
}
hello!
this is my first text file,
You can see how this is done.
输入一行中文也可以

换行可能出现问题,并且每次运行都会删除旧文件生成新文件。

写入文本文件,处理IO异常

import java.io.*;
public class FileWriterTester1 {
    public static void main(String[] args) {
        String fileName = "Hello1.txt";
        try{//将所有IO操作放入try块中
        	//在构造FileWriter的时候参数true表示追加,如果已经存在这个文件,则会在文件末尾追加内容
            FileWriter writer = new FileWriter(fileName,true);
            writer.write("hello!\n");
            writer.write("this is my first text file,\n");
            writer.write("You can see how this is done.\n");
            writer.write("输入一行中文也可以\n");
            writer.close();
        }
        catch (IOException iox) {
            System.out.println("Problem writing"+fileName);
        }
    }
}
hello!
this is my first text file,
You can see how this is done.
输入一行中文也可以
hello!
this is my first text file,
You can see how this is done.
输入一行中文也可以

BufferedWriter类

读文本文件的缓冲器类
具有readLine()方法,可以对换行符进行鉴别,一行一行地读取输入流中的内容
继承自Reader

import java.io.*;

public class BufferedWriterTester {
    public static void main(String[] args) throws IOException{
        String fileName = new String("hello2.txt");
        //用FileWriter对象作为参数构造一个BufferedWriter缓冲的输出流,其不仅能够起到缓冲作用,提高输出效率,而且还有一个写入跨平台换行符的功能newLine()
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName,true));
        out.write("hello!");
        out.newLine();
        out.write("this is another text file using BufferedWriter,");
        out.newLine();
        out.write("so i can use a commom way to start a newline");
        out.newLine();
        out.close();
    }
import java.io.*;

public class BufferedWriterTester1 {
    public static void main(String[] args) {
        try{
            String fileName = new String("hello3.txt");
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
            out.write("hello!");
            out.newLine();
            out.write("this is another text file using BufferedWriter,");
            out.newLine();
            out.write("so i can use a commom way to start a newline");
            out.newLine();
            out.close();
        }
        catch (IOException iox){
            System.out.println("this is an IOException");
        }
    }
}

读文本文件

FileReader类

从文本文件中读取字符
继承自Reader抽象类的子类InputStreamReader

BufferedReader类

读文本文件的缓冲器类
具有readLine()方法,可以对换行符进行鉴别,一行一行地读取输入流中的内容
继承自Reader

读文本文件并显示

FileReader对象:创建后将打开文件,如果文件不存在,会抛出一个IOException
BufferedReader类的readLine()方法:从一个面向字符的输入流中读取一行文本,如果其中不再有数据,返回null
Reader类的read()方法:也可以用来判断文件结束,该方法返回一个表示某个字符的int整形数,如果读到文件末尾,返回-1,据此,可修改本例中的读文件部分:

int c;
while((c = in.read()) != -1){
	System.out.printf((char)c);
}

close()方法:为了操作系统可以更为有效的利用有限的资源,应该在读取完毕之后调用该方法

import java.io.*;

public class BufferedReaderTester {
    public static void main(String[] args) {
        String fileName = new String("Hello.txt");
        try{
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            String line = in.readLine();
            while(line != null){
                System.out.println(line);
                line = in.readLine();
            }
        }
        in.close();
        catch(IOException iox){
            System.out.println("error!");
        }
    }
}

文件复制

import java.io.*;

public class CopyMaker {
    String sourseName,destinationName;
    BufferedReader in;
    BufferedWriter out;
    private boolean openFiles(){
        try{
            in = new BufferedReader(new FileReader(sourseName));
        }
        catch (IOException iox){
            System.out.println("sourse error!");
            return false;
        }try{
            out = new BufferedWriter(new FileWriter(destinationName));
        }
        catch (IOException iox) {
            System.out.println("destination error!");
            return false;
        }
        return true;
    }
    private boolean copyFiles(){
        String line;
        try{
            line = in.readLine();
            while(line != null){
                out.write(line);
                out.newLine();
                line = in.readLine();
            }
        }
        catch (IOException iox){
            System.out.println("copy error!");
            return false;
        }
        return true;
    }
    private boolean closeFile(){
        try{
            in.close();
            out.close();
        }
        catch (IOException iox){
            System.out.println("close error!");
            return false;
        }
        return true;
    }
    public CopyMaker(String sourse,String destination){
        sourseName = sourse;
        destinationName = destination;
    }
    public boolean Copy(){
        return openFiles()&©Files()&&closeFile();
    }
}
//测试类
public class FileCopyTester {
    public static void main(String[] args) {
        CopyMaker copy = new CopyMaker("D:\\java_project\\helloworld\\Hello.txt", "D:\\java_project\\helloworld\\Hello1.txt");
        System.out.println(copy.Copy());
    }
}

写二进制文件

抽象类OutputStream

派生类FileOutputStream
用于一般目的输出(非字符输出)
用于成组字节输出
派生类DataOutputStream
具有写各种基本数据类型的方法
处理流:将数据写到另一个输出流
它在所有的计算机平台上使用同样的数据格式
其中的size方法可以作为计数器,统计写入的字节数

DataOutputStream类的成员

显示java二进制文件 java处理二进制文件_文本文件


显示java二进制文件 java处理二进制文件_文本文件_02

将int写入文件

import java.io.*;
public class FileOutputStreamTester {
    public static void main(String[] args) throws IOException{
        String fileName = "data1.dat";
        int value1 = 255,value2 = 0,value3 = -1;
        //FileOutputStream原生字节流,只识别是一个一个的字节;DataOutputStream处理流,将字节处理为数据
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
        out.writeInt(value1);
        out.writeInt(value2);
        out.writeInt(value3);
        out.close();
    }
}

将文件写入多种数据,统计字节数

import java.io.*;
public class BufferedOutputStreamTester {
    public static void main(String[] args) throws IOException{
        String fileName = "data2.dat";
        DataOutputStream outPut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
        outPut.writeInt(255);
        System.out.println(outPut.size());
        outPut.writeChar(70);
        System.out.println(outPut.size());
        outPut.writeBytes("JAVA");
        System.out.println(outPut.size());
        outPut.close();
    }
}

向文件写一个字节并读取

import java.io.*;
public class FileOutputStreamTester1 {
    public static void main(String[] args) throws IOException{
        String fileName = "try.dat";
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
        //writeByte写一个字节
        out.writeByte(-1);//此时写入文件的为“ff”,-1的补码
        out.close();
        //DataInputStream可以按类型读
        DataInputStream in = new DataInputStream(new FileInputStream(fileName));
        //readByte读入之后赋值给int数据,高位补1,
        int a = in.readByte();//readByte认为其是一个有符号的数,所以高位补符号位
        //toHexString转成十六进制的字符串输出
        System.out.println(Integer.toHexString(a));
        System.out.println(a);
        //往后退一个位置,以便下面重新读出
        in.skip(-1);
        a = in.readUnsignedByte();//无符号的数,高位补0
        System.out.println(Integer.toHexString(a));
        System.out.println(a);
        in.close();
    }
}

读二进制文件

import java.io.*;

public class DataInputStreamTester {
    public static void main(String[] args) {
        int num = 0;
        String fileName = "data1.dat";
        try{
            DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
            num += instr.readInt();
            num += instr.readInt();
            num += instr.readInt();
            System.out.println(num);
            instr.close();
        }
        catch (IOException iox){
            System.out.println("IOx");
        }
    }
}

通过捕获异常控制读取结束

import java.io.*;

public class DataInputStreamTester {
    public static void main(String[] args) {
        int num = 0;
        String fileName = "data1.dat";
        try{
            DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
            try {
                while (true) {
                    num += instr.readInt();
                }
            }catch(EOFException eof){
                System.out.println(num);
                instr.close();
            }
        }
        catch (IOException iox){
            System.out.println("IOx");
        }
    }
}

用字节流读取文本文件

import java.io.*;

public class InputStreamTester1 {
    public static void main(String[] args) throws IOException {
        FileInputStream s = new FileInputStream("Hello.txt");
        int c;
        while((c = s.read()) != -1){
            System.out.println(c);
        }
        s.close();
    }
}

read()方法读取一个字节,转化为[0,255]之间的一个整数,返回一个int,如果读到了文件末尾则返回-1;
write(int)方法写一个字节的低八位,忽略高24位

读写字节

DataOutputStream的writeByte方法
public final void writeByte(int b) throws IOException
将int的嘴不重要字节写入输出流
DataInputStream的readUnsignedByte方法
public final int readUnsignedByte() throws IOException
从输入流中读取1字节存入int的最不重要字节

import java.io.*;
public class CopyBytes {
    public static void main(String[] args) {
        DataInputStream in;
        DataOutputStream out;
        if(args.length != 2){
            System.out.println("Please enter file names");
            return;
        }
        try{
            in = new DataInputStream(new BufferedInputStream(new FileInputStream(args[0])));
            out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(args[1])));
            try{
                while(true) {
                    out.writeByte(in.readByte());
                }
            }
            catch (EOFException eof){
                out.close();
                in.close();
                return;
            }
        }
        catch (FileNotFoundException nfx){
            System.out.println();
        }
        catch (IOException iox){
            System.out.println();
        }
    }
}

File类

File类的作用:
创建、删除文件
重命名文件
判断文件的读写权限及是否存在
设置和查询文件的最近修改时间
构造文件流可以使用File类的对象作为参数

import java.io.*;
public class FileTester {
    public static void main(String[] args) {
        //构造一个File对象,存放文件信息处理文件
        File f = new File("Hello.txt");
        if(f.exists()){		//判断文件是否存在
            f.delete();		//删除文件
        }
        else{
            try{
                f.createNewFile();		//创建文件
            }
            catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }
}

在试图打开文件之前可以使用File类的isFile方法来确定File对象是否代表一个文件而非目录
还可以通过exists方法判断同名文件或路径是否存在,进而采取正确的方法,以免造成误操作

处理压缩文件

压缩流类GZIP

GZIPOutputStream和ZIPOutputStream
可分别把数据压缩成GZIP格式和ZIP格式
GZIPInputStream和ZIPInputStream
可以分别把压缩成GZIP格式或ZIP格式的数据解压缩恢复原状

read()方法读取一个字节,转化为[0,255]之间的一个整数,返回一个int,如果读到了文件末尾,则返回-1
write(int)方法写一个字节的低八位,忽略了高24位

import java.io.*;
import java.util.zip.*;
public class GZIPTester {
    public static void main(String[] args) throws IOException{
        //*******************
        //压缩
        //从Hello.txt读取了文件写到压缩流对象所关联的文件中
        //关联Hello.txt文件,构造一个原生字节的文件输入流对象
        FileInputStream in = new FileInputStream("Hello.txt");
        //构造一个带压缩功能的输出流对象
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream("test.gz"));
        System.out.println("");
        int c;
        while((c = in.read())!= -1){
            out.write(c);
        }
        in.close();
        out.close();
        //****************************
        //解压缩
        System.out.println("");
        //解压缩之后还是一个二进制流
        BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz"))));
        String s;
        //按行读取
        while((s = in2.readLine())!=null){
            System.out.println(s);
        }
        in2.close();
        System.out.println("");
        GZIPInputStream in3 = new GZIPInputStream(new FileInputStream("test.gz"));
        FileOutputStream out2 = new FileOutputStream("newHello.txt");
        while ((c = in3.read())!= -1){
            out2.write(c);
        }
        in3.close();
        out2.close();
    }
}

压缩流类ZIP

可以包含多个文件,可以包含多个目录

import java.io.*;
import java.util.*;
import java.util.zip.*;
public class ZIPOutputStreamTester {
    public static void main(String[] args) throws IOException{
        ZipOutputStream out =new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("test.zip")));

        //压缩多个文件
        for(int i = 0;i < args.length;i++){
            System.out.println("Write file "+args[i]);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[i]));
            //在压缩每个文件之前,首先要将文件的入口标记/开始标记,写到压缩文件中去
            out.putNextEntry(new ZipEntry(args[i]));
            int c;
            while ((c = in.read())!= -1){
                out.write(c);
                in.close();
            }
        }
        out.close();

        //解压缩
        //在二进制流和缓冲流的基础上加一个解压缩流
        ZipInputStream in2 = new ZipInputStream(new BufferedInputStream(new FileInputStream("test.zip")));
        ZipEntry ze;
        //逐个文件恢复,while判断有没有下一个文件
        while((ze = in2.getNextEntry())!=null){
            System.out.println("Reading file "+ze.getName());
            int x;
            while((x = in2.read())!= -1){
                System.out.write(x);
            }
            System.out.println();
        }
        in2.close();
    }
}

解压缩之后的恢复路径

import java.util.*;
import java.util.zip.*;
import java.lang.*;
import java.io.*;

class Unzip{
    byte doc[] = null;//存储解压缩数据的缓冲字节数据
    String Filename = null;//压缩文件名字符串
    String UnZipPath = null;//解压缩路径字符串
    public Unzip(String filename,String unZipPath){     //设置解压缩的路径
        this.Filename = filename;
        this.UnZipPath = unZipPath;
        this.setUnZipPath(this.UnZipPath);
    }
    public Unzip(String filename){
        this.Filename = new String(filename);
        this.UnZipPath = null;
        this.setUnZipPath(this.UnZipPath);
    }
    private void setUnZipPath(String unZipPath){        //统一解压缩路径格式
        if(unZipPath.endsWith("\\")){
            this.UnZipPath = new String(unZipPath);
        }
        else{
            this.UnZipPath = new String(unZipPath+"\\");
        }
    }
    public void doUnZip(){
        try{
            ZipInputStream zipis = new ZipInputStream(new FileInputStream(Filename));
            ZipEntry fEntry = null;
            while((fEntry=zipis.getNextEntry())!=null){     //每一轮处理一个文件
                if(fEntry.isDirectory()){       //判断是路径还是文件名,是路径则创建路径
                    checkFilePath(UnZipPath+fEntry.getName());  //判断路径是否存在,不存在则创建路径
                }
                else{//是文件则解压缩文件
                    String fname = new String(UnZipPath+fEntry.getName());//解压缩的文件名,起始目录+从压缩文件里读出的文件名
                    try{
                        FileOutputStream out = new FileOutputStream(fname);//输出流对象,将解压缩后的内容写到文件里
                        doc = new byte[512];//为了一次多读一些字节
                        int n;
                        while((n = zipis.read(doc,0,512))!=-1){//返回值n是实际读到的长度
                            out.write(doc,0,n);
                        }
                        out.close();
                        out = null;
                        doc = null;
                    }
                    catch (Exception ex){ }
                }
            }
        zipis.close();
        }
        catch (IOException iox){ }
    }
    private void checkFilePath(String dirName) throws IOException{
        File dir = new File(dirName);       //构造一个File对象
        if(!dir.exists()){          //这个对象表示的目录是否存在,如果不存在则创建目录
            dir.mkdirs();       //创建目录
        }
    }
}

public class UnZipTester {
    public static void main(String[] args) {
        String zipFile = args[0];//第一个参数为zip文件名
        String unZipPath = args[1] + "\\";//第二个参数为制定解压缩路径
        Unzip myzip = new Unzip(zipFile,unZipPath);//构造一个Unzip对象,
        myzip.doUnZip();
    }
}