Java文件操作

来源:互联网 发布:道衍和尚 知乎 编辑:程序博客网 时间:2024/05/20 13:38
import java.io.*;import java.nio.channels.FileChannel;public class IOTest {    public static void main(String[] args) throws IOException {        //读取文件        String filePath = "C:/Users/Administrator/Desktop/";        String fileName = "test.txt";        String fileName2 = "copytest.txt";        File f = new File(filePath+fileName);        File f2 = new File(filePath+fileName2);        BufferedReader bfr = new BufferedReader(new FileReader(f));        String str = null;        while((str = bfr.readLine()) != null){            System.out.println(str);        }        //写入文件        //判断文件是否存在        if(f.exists()){            FileOutputStream fos = new FileOutputStream(f);            String s = "123456";            byte[] b = s.getBytes();            fos.write(b);            fos.close();        } else {            System.err.println("文件不存在!");        }/*      //复制文件        //文件输入流        FileInputStream fis = new FileInputStream(f);        FileOutputStream fos = new FileOutputStream(f2);        int buffer;        while((bufferi=fis.read())>0){            fos.write(buffer);        }*/        //复制文件(文件通道)        /*FileInputStream fin = new FileInputStream(f);        FileOutputStream fout = new FileOutputStream(f2);        FileChannel in = fin.getChannel();        FileChannel out = fout.getChannel();        in.transferTo(0, in.size(), out);        */        //文件复制(字符流)        FileReader fr = new FileReader(f);        FileWriter fw = new FileWriter(f2);        char[] c =new char[1024];        fr.read(c);        fw.write(c);        fw.flush();        fw.close();        //文件分割        int num = 5;//分割数量        int len =(int) f.length()/num;//单个文件长度        System.out.println(f.length());        if((int) f.length()%num!=0){//如果文件长度不能被数量整除则+1            num++;        }        fr.read(c);///读入文件数据到数组        for(int i=0;i<num;i++){//循环创建文件            FileWriter fout = new FileWriter(filePath+"cut"+i+".txt");            fout.write(c, len*i, len);//写入到新文件            fout.flush();        }        //文件合并        char[] ch = new char[1024];//缓冲数组        int length = 0;        for(int i=0;i<num;i++){            File ff =new File(filePath+"cut"+i+".txt");            FileReader fin =new FileReader(ff);            fin.read(ch, length, (int) ff.length());            length += (int)ff.length();        }        FileWriter fww = new FileWriter(filePath + "sum.txt");        fww.write(ch);        fww.flush();        //移动文件        /*File mov =new File(filePath+"xx.txt");        mov.renameTo(new File("C:\\Files\\"+mov.getName()));*/    }   }
原创粉丝点击