网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

阅读本文,轻松掌握Java资源文件读取技巧!

GG网络技术分享 2025-11-13 03:10 1


java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;

public class FileHandlingExample {

public static void main {
    // 二、 读取文件内容
    // . 读取文本文件
    String textFilePath = "材料路径/文本文件.txt";
    readTextFile;
    // . 读取二进制文件
    String binaryFilePath = "材料路径/二进制文件.bin";
    readBinaryFile;
    // 三、处理文件路径
    // 获取编码后的路径
    String encodedPath = encodeFilePath;
    // 解码后获取路径
    String decodedPath = decodeFilePath;
    System.out.println;
}
private static void readTextFile {
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(
                getClass.getClassLoader.getResourceAsStream, StandardCharsets.UTF_8))) {
        StringBuilder sb = new StringBuilder;
        String line;
        while ) != null) {
            sb.append.append;
        }
        String content = sb.toString;
        System.out.println;
    } catch  {
        e.printStackTrace;
    }
}
private static void readBinaryFile {
    try .getClassLoader.getResourceAsStream;
         ByteArrayOutputStream baos = new ByteArrayOutputStream) {
        byte buffer = new byte;
        int len;
        while ) != -1) {
            baos.write;
        }
        byte fileBytes = baos.toByteArray;
        System.out.println;
        for  {
            System.out.printf;
        }
        System.out.println;
    } catch  {
        e.printStackTrace;
    }
}
private static String encodeFilePath {
    String encodedPath = null;
    try {
        encodedPath = URLEncoder.encode);
    } catch  {
        e.printStackTrace;
    }
    return encodedPath;
}
private static String decodeFilePath {
    String decodedPath = null;
    try {
        decodedPath = URLDecoder.decode);
    } catch  {
        e.printStackTrace;
    }
    return decodedPath;
}

}

这段代码展示了怎么读取文本文件和二进制文件,并处理文件路径中的编码问题。对于读取文本文件,用BufferedReader来逐行读取内容。对于二进制文件,用InputStream来读取字节数据。还有啊,给了对文件路径进行编码和优良码的方法,以确保在文件路径中包含特殊字符时Neng够正确处理。

标签:

提交需求或反馈

Demand feedback