国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Java 各種讀取文件方法以及文件合并

2019-11-14 21:12:05
字體:
供稿:網(wǎng)友
java 各種讀取文件方法以及文件合并JAVA讀取文件1、按字節(jié)讀取文件內(nèi)容2、按字符讀取文件內(nèi)容3、按行讀取文件內(nèi)容

4、隨機(jī)讀取文件內(nèi)容

public class ReadFromFile {    /**     * 以字節(jié)為單位讀取文件,常用于讀二進(jìn)制文件,如圖片、聲音、影像等文件。     */    public static void readFileByBytes(String fileName) {        File file = new File(fileName);        InputStream in = null;        try {            System.out.access(String fileName) {        RandomAccessFile randomFile = null;        try {            System.out.println("隨機(jī)讀取一段文件內(nèi)容:");            // 打開一個(gè)隨機(jī)訪問文件流,按只讀方式            randomFile = new RandomAccessFile(fileName, "r");            // 文件長(zhǎng)度,字節(jié)數(shù)            long fileLength = randomFile.length();            // 讀文件的起始位置            int beginIndex = (fileLength > 4) ? 4 : 0;            // 將讀文件的開始位置移到beginIndex位置。            randomFile.seek(beginIndex);            byte[] bytes = new byte[10];            int byteread = 0;            // 一次讀10個(gè)字節(jié),如果文件內(nèi)容不足10個(gè)字節(jié),則讀剩下的字節(jié)。            // 將一次讀取的字節(jié)數(shù)賦給byteread            while ((byteread = randomFile.read(bytes)) != -1) {                System.out.write(bytes, 0, byteread);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (randomFile != null) {                try {                    randomFile.close();                } catch (IOException e1) {                }            }        }    }    /**     * 顯示輸入流中還剩的字節(jié)數(shù)     */    private static void showAvailableBytes(InputStream in) {        try {            System.out.println("當(dāng)前字節(jié)輸入流中的字節(jié)數(shù)為:" + in.available());        } catch (IOException e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        String fileName = "C:/temp/newTemp.txt";        ReadFromFile.readFileByBytes(fileName);        ReadFromFile.readFileByChars(fileName);        ReadFromFile.readFileByLines(fileName);        ReadFromFile.readFileByRandomAccess(fileName);    }}

5、在貼個(gè)合并文件的代碼,每個(gè)文件介紹之后都加入換行代碼,其中使用了普通Io和Nio,這個(gè)是我自己的需求,文件目錄例如:c:/文件夾1/文件夾2/test.txt,代碼中傳入?yún)?shù)為c:/文件夾1

package mergesql;import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.Date;import java.util.List;import java.util.Scanner;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;/** * 合并sql腳本文件工具類 *  * @author webapp *  */public class MergeSqlFileUtil extends JFrame implements ActionListener {    /**     *      */    private static final long serialVersionUID = 1L;    private final static String fileName = ".sql";    /**     * 獲取當(dāng)前路徑下的所有文件中     *      * @time 2014年8月25日     * @auther yuxu.feng     * @param filepath     * @return     */    private static List<File> getFiles(String filepath) {        File file = new File(filepath);        if (!file.exists() | file.listFiles(new MyFileFileter()) == null)            return null;        List<File> fileList = Arrays                .asList(file.listFiles(new MyFileFileter()));        // 最好在這里把 文件過濾掉 只獲取文件夾        return sortFolder(fileList);    }    /**     * 按照文件夾按照文件名進(jìn)行升序 或按著文件名的名字進(jìn)行升序     *      * @time 2014年8月25日     * @auther yuxu.feng     * @param files     * @return     */    private static List<File> sortFolder(List<File> files) {        if (files.size() == 0)            return null;        Collections.sort(files, new Comparator<File>() {            @Override            public int compare(File o1, File o2) {                if (o1.isDirectory() && o2.isFile())                    return -1;                if (o1.isFile() && o2.isDirectory())                    return 1;                if (o1.isDirectory() && o2.isDirectory())                    return sortFolderName(o1.getName(), o2.getName());                else                    return 0;            }        });        return files;    }    /**     * 根據(jù)文件夾名稱排序     *      * @time 2014年8月25日     * @auther yuxu.feng     * @param startName     * @param endName     * @return     */    private static int sortFolderName(String startName, String endName) {        if ((parseFloderName(startName) - parseFloderName(endName)) >= 0)            return 1;        else            return -1;    }    /**     * 將文件夾的名字(格式為 A.B.C.D) 轉(zhuǎn)換為long型的數(shù)字     *      * @time 2014年8月25日     * @auther yuxu.feng     * @param floderName     * @return     */    private static long parseFloderName(String floderName) {        Scanner sc = new Scanner(floderName).useDelimiter("http://.");        return (sc.nextLong() << 24) + (sc.nextLong() << 16)                + (sc.nextLong() << 8) + (sc.nextLong());    }    /**     * 使用NIO進(jìn)行文件合并     *      * @time 2014年8月25日     * @auther yuxu.feng     * @param filepath     */    public static void mergerNIO(String filepath) {        SimpleDateFormat fd = new SimpleDateFormat("yyyyMMddHHmmss");        String nowTime = fd.format(new Date());        List<File> fileList = getFiles(filepath);        if (fileList == null)            return;        File fout = new File(filepath + File.separator + nowTime + fileName);        try {            @SuppressWarnings("resource")            FileChannel mFileChannel = new FileOutputStream(fout).getChannel();            FileChannel inFileChannel;            List<File> files = null;            for (File folder : fileList) {                if (folder.isDirectory()) {                    files = Arrays.asList(folder.listFiles());                    // sortFolder(files);                    for (File fin : files) {                        // if (fin.getName().endsWith(fileName)) {                        // inFileChannel = new FileInputStream(fin)                        // .getChannel();                        // inFileChannel.transferTo(0, inFileChannel.size(),                        // mFileChannel);                        //                        // inFileChannel.close();                        // }                        if (fin.getName().endsWith(fileName)) {                            inFileChannel = new FileInputStream(fin)                                    .getChannel();                            inFileChannel.transferTo(0, inFileChannel.size(),                                    mFileChannel);                            inFileChannel.close();                            mFileChannel.write(ByteBuffer.wrap("/r/n"                                    .getBytes()));                        }                    }                }            }            mFileChannel.close();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 使用普通IO進(jìn)行拷貝文件     *      * @time 2014年8月27日     * @auther yuxu.feng     * @param filepath     */    public static void mergerIO(String filepath) {        SimpleDateFormat fd = new SimpleDateFormat("yyyyMMddHHmmss");        String nowTime = fd.format(new Date());        List<File> fileList = getFiles(filepath);        if (fileList == null)            return;        File fout = new File(filepath + File.separator + nowTime + fileName);        BufferedInputStream inBuff = null;        BufferedOutputStream outBuff = null;        try {            outBuff = new BufferedOutputStream(new FileOutputStream(fout));            List<File> files = null;            FileInputStream finput = null;            for (File folder : fileList) {                if (folder.isDirectory()) {                    files = Arrays.asList(folder.listFiles());                    for (File fin : files) {                        finput = new FileInputStream(fin);                        inBuff = new BufferedInputStream(finput);                        byte[] b = new byte[finput.available()];                        int len;                        while ((len = inBuff.read(b)) != -1) {                            outBuff.write(b, 0, len);                        }                        inBuff.close();                        outBuff.flush();                    }                }            }            outBuff.close();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     *      * @time 2014年8月27日     * @auther yuxu.feng     * @param filepath     */    public static void mergeByBuffWriter(String filepath) {        SimpleDateFormat fd = new SimpleDateFormat("yyyyMMddHHmmss");        String nowTime = fd.format(new Date());        List<File> fileList = getFiles(filepath);        if (fileList == null)            return;        try {            File fout = new File(filepath + File.separator + nowTime + fileName);// 輸出文件位置            List<File> files = null;            BufferedReader br = null;            BufferedWriter bw = null;            FileOutputStream fops = new FileOutputStream(fout);            bw = new BufferedWriter(new OutputStreamWriter(                    fops, "UTF-8"));//            bw.write('/ufeff'); 帶有bom格式的utf-8//            fops.write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF}); 帶有bom格式的utf-8            for (File folder : fileList) {                if (folder.isDirectory()) {                    files = Arrays.asList(folder.listFiles());                    for (File fin : files) {                        FileInputStream finput = new FileInputStream(fin);                        br = new BufferedReader(new InputStreamReader(finput,                                "UTF-8"));                        char[] cbuf = new char[finput.available()];                        int len = cbuf.length;                        int off = 0;                        int ret = 0;                        while ((ret = br.read(cbuf, off, len)) > 0) {                            off += ret;                            len -= ret;                        }                        br.close();                        bw.write(cbuf, 0, off);                                                bw.newLine();                        bw.flush();                    }                }            }            bw.close();        } catch (IOException e) {            e.printStackTrace();        }    }    // /////////////////swing界面////////////////////////    private JLabel lblUsername;    private JTextField tfUsername;    private JButton btnOK;    private JButton btnExit;    public MergeSqlFileUtil() {        JPanel p1 = new JPanel();        p1.setLayout(new BorderLayout());        lblUsername = new JLabel("合并的文件目錄:");        tfUsername = new JTextField(20);        p1.add(lblUsername, BorderLayout.WEST);        p1.add(tfUsername, BorderLayout.EAST);        JPanel p2 = new JPanel();        p2.setLayout(new BorderLayout());        JPanel p3 = new JPanel();        btnOK = new JButton("確定");        btnOK.addActionListener(this);        btnExit = new JButton("取消");        btnExit.addActionListener(this);        p3.add(btnOK);        p3.add(btnExit);        this.add(p1, BorderLayout.NORTH);        this.add(p2, BorderLayout.CENTER);        this.add(p3, BorderLayout.SOUTH);        this.setLocation(400, 300);        this.setSize(350, 110);        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);        this.setVisible(true);    }    @Override    public void actionPerformed(ActionEvent e) {        if (e.getActionCommand().equals("確定")) {            String path = tfUsername.getText();            Long endIo = System.currentTimeMillis();            MergeSqlFileUtil.mergerIO(path);//            MergeSqlFileUtil.mergeByBuffWriter(path);            Long endNio = System.currentTimeMillis();            JOptionPane.showMessageDialog(this, "運(yùn)行時(shí)間為:" + (endNio - endIo));        } else if (e.getActionCommand().equals("取消")) {            System.exit(0);        }    }    public static void main(String[] args) {        new MergeSqlFileUtil();    }}
package mergesql;import java.io.File;import java.io.FileFilter;public class MyFileFileter implements FileFilter{    @Override    public boolean accept(File pathname) {        if(pathname.isDirectory()){            return true;        }        return false;    }}


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沈丘县| 乳山市| 甘谷县| 屏东市| 社会| 汶川县| 旅游| 涟水县| 永仁县| 南木林县| 洪江市| 崇明县| 乌拉特前旗| 盐亭县| 志丹县| 保康县| 河间市| 开阳县| 钟山县| 望江县| 清河县| 孝昌县| 左贡县| 招远市| 山阳县| 平顺县| 柘城县| 临沧市| 册亨县| 留坝县| 邓州市| 东莞市| 茂名市| 贵溪市| 德惠市| 高安市| 淅川县| 汝南县| 高邮市| 凤山市| 讷河市|