FileUtil

该博客可能围绕Java进行读写文件操作展开,涉及Java语言在文件读写方面的技术内容,属于信息技术领域后端开发范畴。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;

public class FileUtil {

    /**
     * 按行读取文件
     */
    public static void ReadFileByLine(String filename) {
        File file = new File(filename);
        InputStream is = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            is = new FileInputStream(file);
            reader = new InputStreamReader(is);
            bufferedReader = new BufferedReader(reader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedReader)
                    bufferedReader.close();
                if (null != reader)
                    reader.close();
                if (null != is)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按字节读取文件
     *
     * @param filename
     */
    public static void ReadFileByBytes(String filename) {
        File file = new File(filename);
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            int index = 0;
            while (-1 != (index = is.read())) {
                System.out.write(index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("-----------------------------------");
        try {
            is = new FileInputStream(file);
            byte[] tempbyte = new byte[1000];
            int index = 0;
            while (-1 != (index = is.read(tempbyte))) {
                System.out.write(tempbyte, 0, index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按字符读取文件
     *
     * @param filename
     */
    public static void ReadFileByChar(String filename) {
        File file = new File(filename);
        InputStream is = null;
        Reader isr = null;
        try {
            is = new FileInputStream(file);
            isr = new InputStreamReader(is);
            int index = 0;
            while (-1 != (index = isr.read())) {
                System.out.print((char) index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
                if (null != isr)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过OutputStreamWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByOutputStream(String filename) {
        File file = new File(filename);
        FileOutputStream fos = null;
        // BufferedOutputStream bos = null;
        OutputStreamWriter osw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            osw.write("Write2FileByOutputStream");
            // bos = new BufferedOutputStream(fos);
            // bos.write("Write2FileByOutputStream".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过BufferedWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByBuffered(String filename) {
        File file = new File(filename);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            bw.write("Write2FileByBuffered");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过FileWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByFileWriter(String filename) {
        File file = new File(filename);
        FileWriter fw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("Write2FileByFileWriter");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fw) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

 

### Android 中 `FileUtil` 的使用教程与示例 #### 一、简介 `FileUtil` 是一个常用的工具类,在 Android 开发中用于处理文件操作。它提供了多种便捷的方法来管理本地文件,例如读取文件内容、写入数据到文件以及检查文件是否存在等功能。 --- #### 二、核心功能概述 以下是 `FileUtil` 提供的主要功能及其对应的实现方式: 1. **判断文件是否存在** 可通过调用静态方法 `isFileExist(String path)` 来检测指定路径下的文件是否存在[^2]。 ```java boolean isExists = FileUtil.isFileExist("/path/to/file.txt"); ``` 2. **读取文件为字节数组** 使用 `readFileByBytes(String filePath)` 方法可以将整个文件的内容读取为字节数组[^3]。 ```java byte[] imageData = FileUtil.readFileByBytes("/storage/emulated/0/image.png"); ``` 3. **获取系统目录** 支持获取各种类型的系统目录并支持自定义子路径创建[^5]。 - 获取应用缓存目录: ```java String cacheDir = FileUtil.getCacheDirectory(context); ``` - 创建带自定义路径的外部存储目录: ```java String customExternalPath = FileUtil.getExternalFilesDir(context, "/my_custom_folder/"); ``` 4. **格式化文件路径** 对输入的字符串进行标准化处理,确保路径合法有效。 ```java String formattedPath = FileUtil.formatFilePath("/../invalid/path//example.txt"); ``` 5. **判断外置存储状态** 检查设备上的 SD 卡或其他可移动存储介质是否可用。 ```java boolean isAvailable = FileUtil.isExternalStorageAvailable(); ``` --- #### 三、综合示例代码 以下是一个完整的例子,展示如何利用 `FileUtil` 进行常见的文件操作: ```java import android.content.Context; public class FileUtilsExample { private Context context; public FileUtilsExample(Context context) { this.context = context; } /** * 判断文件是否存在并打印结果 */ public void checkFileExistence() { String filePath = "/storage/emulated/0/example_file.txt"; if (FileUtil.isFileExist(filePath)) { System.out.println("The file exists."); } else { System.out.println("The file does not exist."); } } /** * 将图片文件转换为字节数组 */ public void readImageAsByteArray() { try { String imagePath = "/storage/emulated/0/sample_image.jpg"; byte[] imageBytes = FileUtil.readFileByBytes(imagePath); if (imageBytes != null && imageBytes.length > 0) { System.out.println("Image successfully converted to byte array with size: " + imageBytes.length); } else { System.out.println("Failed to convert the image to a byte array."); } } catch (Exception e) { e.printStackTrace(); } } /** * 获取外部存储中的特定目录 */ public void getCustomExternalDirectory() { String externalPath = FileUtil.getExternalFilesDir(context, "/custom_directory/"); System.out.println("Custom External Directory Path: " + externalPath); } } ``` --- #### 四、注意事项 1. 需要声明权限:如果涉及访问外部存储,则需在 `AndroidManifest.xml` 文件中添加如下权限声明: ```xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` 2. 动态请求权限:对于 API Level >= 23 的设备,还需要动态申请运行时权限。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值