欢迎访问宙启技术站
智能推送

Java函数实现对文件读写的简易方法

发布时间:2023-05-30 08:18:42

Java语言中提供了许多方法可以对文件进行读写操作,比如使用字节流,字符流和NIO等方式。在本文中,我们将使用字节流和字符流的方式来实现对文件的读写操作,并提供简易的方法,可以在实际开发中使用。

一、文件读操作方法

1.使用字节流方式进行文件读操作

使用字节流方式可以读取文件中所有的字节,以下是一个简单的方法,实现了从给定文件路径读出数据的功能。其中使用了FileInputStream类和ByteArrayOutputStream类来操作文件。

/**

 * 读取文件数据

 *

 * @param filepath 文件路径

 * @return 文件字节数组

 * @throws IOException

 */

public static byte[] readFileByBytes(String filepath) throws IOException {

    File file = new File(filepath);

    if (!file.exists()) {

        throw new FileNotFoundException("File not exists!");

    }

    try (FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

        byte[] readBytes = new byte[1024];

        int readLen;

        while ((readLen = fis.read(readBytes)) > 0) {

            bos.write(readBytes, 0, readLen);

        }

        return bos.toByteArray();

    }

}

2.使用字符流方式进行文件读操作

使用字符流方式可以读取文件中的字符数据,以下是一个简单的方法,实现了从给定文件路径读出数据的功能。其中使用了FileReader类和BufferedReader类来操作文件。

/**

 * 读取文件数据

 *

 * @param filepath 文件路径

 * @return 文件字符串

 * @throws IOException

 */

public static String readFileByChars(String filepath) throws IOException {

    File file = new File(filepath);

    if (!file.exists()) {

        throw new FileNotFoundException("File not exists!");

    }

    StringBuilder sb = new StringBuilder();

    try (FileReader fr = new FileReader(file); BufferedReader bf = new BufferedReader(fr)) {

        String line;

        while ((line = bf.readLine()) != null) {

            sb.append(line);

        }

        return sb.toString();

    }

}

二、文件写操作方法

1.使用字节流方式进行文件写操作

使用字节流方式可以写出二进制数据到文件中,以下是一个简单的方法,实现了写入数据到指定文件路径的功能。其中使用了FileOutputStream类和ByteArrayInputStream类来操作文件。

/**

 * 写入数据到文件

 *

 * @param data     数据字节数组

 * @param filepath 文件路径

 * @throws IOException

 */

public static void writeFileByBytes(byte[] data, String filepath) throws IOException {

    try (FileOutputStream fos = new FileOutputStream(filepath); ByteArrayInputStream bis = new ByteArrayInputStream(data)) {

        byte[] writeBytes = new byte[1024];

        int writeLen;

        while ((writeLen = bis.read(writeBytes)) != -1) {

            fos.write(writeBytes, 0, writeLen);

        }

        fos.flush();

    }

}

2.使用字符流方式进行文件写操作

使用字符流方式可以写出文本数据到文件中,以下是一个简单的方法,实现了写入数据到指定文件路径的功能。其中使用了FileWriter类和BufferedWriter类来操作文件。

/**

 * 写入数据到文件

 *

 * @param data     数据字符串

 * @param filepath 文件路径

 * @throws IOException

 */

public static void writeFileByChars(String data, String filepath) throws IOException {

    try (FileWriter fw = new FileWriter(filepath, false); BufferedWriter bw = new BufferedWriter(fw)) {

        bw.write(data);

        bw.flush();

    }

}

以上是文件读写操作的简易方法,通过这些方法可以实现对文件的常用操作,可以在日常开发中使用。同时还要注意的是,在进行文件操作时一定要注意异常处理,保证程序的健壮性和正确性。