有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助来提高代码的效率

我总是使用这种方法来轻松地读取文件的内容。它足够有效吗?1024适合缓冲区大小吗

public static String read(File file) {
    FileInputStream stream = null;
    StringBuilder str = new StringBuilder();

    try {
        stream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
    }

    FileChannel channel = stream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    try {
        while (channel.read(buffer) != -1) {
            buffer.flip();

            while (buffer.hasRemaining()) {
                str.append((char) buffer.get());
            }

            buffer.rewind();
        }
    } catch (IOException e) {
    } finally {
        try {
            channel.close();
            stream.close();
        } catch (IOException e) {
        }
    }

    return str.toString();
}

共 (3) 个答案

  1. # 1 楼答案

    你可能会发现这已经足够快了

    String text = FileUtils.readFileToString(file);
    

    好的,这使用默认的缓冲区大小8K。然而,我发现更大的尺寸,比如64K,可能会有轻微的不同

  2. # 3 楼答案

    试试下面的方法,它应该很有效:

    public static String read(File file)
    {
        StringBuilder str = new StringBuilder();
    
        BufferedReader in = null;
    
        String line = null;
    
        try
        {
            in = new BufferedReader(new FileReader(file));
    
            while ((line = in.readLine()) != null)
               str.append(line);
    
            in.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    
        return str.toString();
    }