Java 各种读取文件方法以及文件合并

JAVA读取文件

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容

public class ReadFromFile {
    /**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("以字节为单位读取文件内容,一次读多个字节:");
            // 一次读多个字节
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            // 读入多个字节到字节数组中,byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字节:");
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
                // 但如果这两个字符分开显示时,会换两次行。
                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                if (((char) tempchar) != ‘\r‘) {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字节:");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != ‘\r‘)) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == ‘\r‘) {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容:");
            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            // 将一次读取的字节数赋给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) {
                }
            }
        }
    }

    /**
     * 显示输入流中还剩的字节数
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + 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、在贴个合并文件的代码,每个文件介绍之后都加入换行代码,其中使用了普通Io和Nio,这个是我自己的需求,文件目录例如:c:/文件夹1/文件夹2/test.txt,代码中传入参数为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";

    /**
     * 获取当前路径下的所有文件中
     *
     * @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);
    }

    /**
     * 按照文件夹按照文件名进行升序 或按着文件名的名字进行升序
     *
     * @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;
    }

    /**
     * 根据文件夹名称排序
     *
     * @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) 转换为long型的数字
     *
     * @time 2014年8月25日
     * @auther yuxu.feng
     * @param floderName
     * @return
     */
    private static long parseFloderName(String floderName) {
        Scanner sc = new Scanner(floderName).useDelimiter("\\.");
        return (sc.nextLong() << 24) + (sc.nextLong() << 16)
                + (sc.nextLong() << 8) + (sc.nextLong());
    }

    /**
     * 使用NIO进行文件合并
     *
     * @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进行拷贝文件
     *
     * @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, "运行时间为:" + (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;
    }

}
时间: 2024-08-06 23:56:46

Java 各种读取文件方法以及文件合并的相关文章

Java API 读取HDFS的单文件

HDFS上的单文件: -bash-3.2$ hadoop fs -ls /user/pms/ouyangyewei/data/input/combineorder/repeat_rec_category Found 1 items -rw-r--r-- 2 deploy supergroup 520 2014-08-14 17:03 /user/pms/ouyangyewei/data/input/combineorder/repeat_rec_category/repeatRecCategor

Java中读取xml方法

package zaxiang; import java.io.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class

Java读取配置文件方法及文件路径注意事项

一.方法请见代码中的注释说明,需要注意的就是对于文件路径的读取方式,不同的方法,对路径的解释是不一样的. 1 package com.yard39.ProperTiesFileReader.Test; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java

java _io_commons读取、写出文件

//读取文件转换成字符串 String s=FileUtils.readFileToString(new File("D:\\d\\write.txt"),"UTF-8"); //读取文件转换成字节数组 byte[] datas=FileUtils.readFileToByteArray(new File("D:\\d\\write.txt")); //逐行读取,返回类型是List List<String> list=FileUtil

Java逐行读取文件有多少种方法?

如果每个线程使用的变量都是其它线程不会读取或修改的,那么就不存在一致性问题.同样,如果变量是只读的,多个线程同时读取该变量也不会有一致性问题.否则,将会出现不一致性问题.为了解决数据不一致问题,必须引入某些机制使线程间同步. 当变量修改时间多于一个存储器访问周期,同时读.写操作又相互交替时,潜在的不一致性就会出现.如下图所示: 此时,线程B读取到的数据是错误的.使用一把锁能够解决上述问题: 下面介绍线程的三种同步机制: 1.互斥量pthread_mutex_t 互斥量就是锁,对某段临界区进行加锁

java各种读取properties文件方法

java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便. 例如: test.properties ------------------------------------------------------ ##################

[Java]读取文件方法大全(转)

[Java]读取文件方法大全 1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile {    /**     * 以字节为单位读取文件,常用于读二进制文件,如图片.声音.影像等文件.     */    public static void readFileByBytes(String fileName) {        File file = new File(fileName);        Input

【转】Java读取文件方法大全

本文转自:http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html#undefined 目录: 按字节读取文件内容 按字符读取文件内容 按行读取文件内容 随机读取文件内容 将内容追加到文件尾部 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片.声音.影像等文件. */ public static void readFileByBytes(String fil

Java获取路径方法&amp;相对路径读取xml文件方法

Java获取路径方法&相对路径读取xml文件方法 (1).request.getRealPath("/");//不推荐使用获取工程的根路径 (2).request.getRealPath(request.getRequestURI());//获取jsp的路径,这个方法比较好用,可以直接在servlet和jsp中使用 (3).request.getSession().getServletContext().getRealPath("/");//获取工程的根路径