java学习笔记(3)

  java中文件处理的api, 文件处理就是增删改查,以及文件输入输出流的处理, File类, File类的实例有以下方法:

  getName();  getPrant();  getPath();  getAbsolutePath();  exists();  isFile()  idDirectory();  isAbsolute();  delete();  mkdir();  mkdirs();  setRealOnley();  length();  lastModified();  list(); listFile();

运行下面代码

复制代码
import java.io.*;
public class GetFileInfo {
    public static void main (String[] arr) {
        String filePath = "GetFileInfo.java";
        File file = new File(filePath);
        System.out.println( "getName: " + file.getName() );
        System.out.println( "is exits : " + file.exists() );
        System.out.println( "getAbsolutePath : " + file.getAbsolutePath() );
        System.out.println( "canExecute" + file.canExecute() );
        System.out.println( "can read :" + file.canRead() );
        System.out.println( "can write :" + file.canWrite() );
        System.out.println( "getParent :" + file.getParent() );
        System.out.println( "file length :" + file.length() );
        System.out.println( "file last modified :" + file.lastModified() );
        System.out.println( "file : true or false :" + file.isFile() );
        System.out.println( "file is directory :" + file.isDirectory() );
    }
}
复制代码

 

  FileInputStream; FileoutputStream, 文件输入输出流通过实例来说明最快最简单, 一个Demo,作用是显示上次运行该exe文件时系统的信息, 以及保存当前的系统信息, java的类型真多, 转换类型都要转疯了:

运行下面代码

复制代码
import java.io.*;
import java.util.*;
import java.text.*;
import java.util.Date.*;

public class FileInAndOut {
    private static String filePath = "./myProgram.cfg";
    private static File file = new File(filePath);
    private static int runCount = 0;
    private static Date date = new Date();
    private static String os = "window";
    private static DateFormat df = new SimpleDateFormat("yy-MM-dd");
    private static String sDate = df.format( date );
    private static String dataStr = "";

    public static void main(String[] arg) {
        loadConfig();
        if( dataStr.isEmpty() ) {
            System.out.println("_first_init");
        }else{
            System.out.println( runCount );
            System.out.println( date );
            System.out.println( os );
        };
        putConfig();
    }

    private static void loadConfig () {
        try {
            if( !file.exists() ) {
                file.createNewFile();
            };

            byte[] data = new byte[64];
            FileInputStream fs = new FileInputStream(file);
            int rs = 0;
            // if is be OK , rs is index of the data;
            // if( (rs = fs.read(data))!=-1 ) yeah ..
            while ( (rs = fs.read(data)) > 0 ) {
                dataStr += new String(data, 0 , rs);
                //slice data ; data has all the data from fs;
                //System.out.println( new String(data, 0 , 10) );
            };
            System.out.println( dataStr );
            if( !dataStr.isEmpty() ) {
                String[] sets = dataStr.split(",");
                //System.out.println( "sets" );
                //System.out.println( sets[0] );
                //System.out.println( sets[1] );
                //System.out.println( sets[2] );
                runCount = Integer.parseInt(sets[0]);
                sDate = sets[1];
                os = sets[2];
            };
        }catch( IOException e ) {
            e.printStackTrace();
        };
    }

    private static void putConfig () {
        String dataStr;
        try {
            if( !file.exists() ) {
                file.createNewFile();
            };
            runCount++;
            dataStr = runCount + "," + sDate + "," + os;
            // should we have to use getBytes?
            byte[] data = dataStr.getBytes();
            FileOutputStream fout = new FileOutputStream(file);
            fout.write( data );
            fout.flush();
            fout.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
复制代码

 

  

  有关java输入输出io的FileReader和FileWriter,BufferedWriter,的使用实例:

运行下面代码

复制代码
import java.io.*;

// we used File , FileWriter, BufferedWriter;
// FileReader , BufferedReader;
public class Student {
    public static void main (String[] args) {
        String content[] = {"longtimenosee","howdoyoudo","keepintouch"};
        File file = new File("./word.txt");

        try{
            if( !file.exists() ) {
                file.createNewFile();
            };
            FileWriter fw = new FileWriter(file);
            BufferedWriter bfw = new BufferedWriter( fw );
            int i = 0;
            for( i = 0; i<content.length; i++) {
                bfw.write( content[i] );
                bfw.newLine();
            };
            bfw.close();
            fw.close();
        }catch( Exception e) {
            e.printStackTrace();
        }
        
        try{
            FileReader fr = new FileReader(file);
            BufferedReader bfr = new BufferedReader(fr);
            String s = null;
            // this is readLine , not read;
            while( (s = bfr.readLine()) != null ) {
                System.out.println( s );
            };
            bfr.close();
            fr.close();
        }catch( Exception e ) {
            e.printStackTrace();
        }
    }
}
复制代码

 

  FileReader和BufferedReader相同点和不同点

    相同点:都是使用字符流写文件。
    不同点:前者采用缓冲区,可以预读一些准备写入的数据,增加写入文件时的效率,
      而后者则没有这个功能。具体的在BufferedWriter的API DOC中有说明。

 

  WriterObjectReadObject的使用,把对象数据保存到物理文件中,以后可以再读取出来:

运行下面代码

复制代码
import java.io.*;

//JUST use class be OK;
class Worker implements Serializable{
    private String name;
    private String sex;
    private int age;
    public void setName ( String name ) {
        this.name = name;
    }
    public String getName () {
        return this.name;
    }

    public void setSex ( String sex ) {
        this.sex = sex;
    }
    public String getSex () {
        return this.sex;
    }

    public void setAge ( int age ) {
        this.age = age;
    }
    public int getAge () {
        return this.age;
    }
}

//how to use readObject and WriteObject method; 
public class WriteReadObject{

    public static void main(String[] args) {
        try {
            Worker worker = new Worker();
            worker.setAge( 27 );
            worker.setName( "nono" );
            worker.setSex( "male" );
            FileOutputStream fout = new FileOutputStream("./worker.txt");
            ObjectOutputStream oops = new ObjectOutputStream( fout );
            //oops.writeObject( new String( " " ) );
            oops.writeObject( worker );
        }catch(Exception e) {
            e.printStackTrace();
        };

        try{
            FileInputStream fin = new FileInputStream("./worker.txt");
            ObjectInputStream ois = new ObjectInputStream( fin );
            Worker wk = (Worker) ois.readObject();90
            System.out.println( wk.getName() );
            System.out.println( wk.getAge() );
            System.out.println( wk.getSex() );
        }catch( Exception e) {
            e.printStackTrace();
        }
    }    
}
复制代码

 

  例子是复制文件夹和文件的操作,包括了使用new File新建文件对象,以及通过new FileInputStream:new FileOutputStream对文件对象的数据进行输入输出操作, 新建比特new byte[number]保存数据到文件中, fileInstance.mkdir(),fileInstance.createNewFile(), fileInsance.write("012345678");

运行下面代码

复制代码
import java.io.*;

public class CopyFile {
    //muti with fileList;
    private static void copy (File[] s, File d) {
        if( !(d.exists()) ) {
            System.out.println("wrong dest target!");
        };
        try {
            for( int i=0 ; i < s.length; i++ ) {
                if( s[i].isFile() ) {
                    // the input argument should be an File instance;
                    FileInputStream fis = new FileInputStream( s[i] );
                    File destFile = new File(d.getAbsolutePath() + "\\" + s[i].getName());
                    if( !destFile.exists() ) {
                        destFile.createNewFile();
                    };
                    //System.out.println( d.getAbsolutePath() + "\\" + s[i].getName() );
                    FileOutputStream fos = new FileOutputStream( destFile );
                    int count = fis.available();
                    // new byte;
                    byte[] fileInputData = new byte[count];
                    //the return is index;
                    //if( fis.read(fileInputData) != -1) ; what ever it's depends you ;
                    while( fis.read(fileInputData) != -1) {
                        //System.out.println( fileInputData );
                        fos.write(fileInputData);
                    };
                    fis.close();
                    fos.close();
                }else if( s[i].isDirectory() ) {
                    System.out.println( File.separator );
                    File des = new File( d.getAbsolutePath() + "\\" + s[i].getName() );
                    des.mkdir();
                    //iterator the directory;
                    copy( s[i].listFiles(), des );
                };
            };
        }catch( Exception e ) {
            e.printStackTrace();
        }
    };
    public static void main(String[] args) {
        File sourceFile = null;
        File destFile = null;
        sourceFile = new File("C:/Users/Administrator/Desktop/game/java/2.24");
        destFile = new File("C:/Users/Administrator/Desktop/game/copyJavaFiles");

        if( !sourceFile.exists() ) {
            System.out.println("source is't exists!");
        };

        destFile.mkdir();
        copy(sourceFile.listFiles(), destFile);
    }
}
复制代码

本文作者:方方和圆圆

本文链接:https://www.cnblogs.com/diligenceday/p/4298764.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   方方和圆圆  阅读(181)  评论(0编辑  收藏  举报

再过一百年, 我会在哪里?

💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
点击右上角即可分享
微信分享提示