Java CharsetEncoder averageBytesPerChar()方法及示例

Java CharsetEncoder averageBytesPerChar()方法及示例

averageBytesPerChar() 方法是 java.nio.charset.CharsetEncoder 的一个内置方法,它返回提供的每个输入字符将产生的平均字节数。因此,启发式数值被用来估计给定输入序列所需的输出缓冲区的大小。

语法:

public final float averageBytesPerChar()

参数 :该函数不接受任何参数。

返回值 :该函数返回每个输入字符所产生的平均字节数。

下面是上述函数的实现。

程序 1 :

// Java program to implement
// the above function
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
  
public class Main {
    public static void main(String[] args) throws Exception
    {
  
        // Gets the new encoder
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
  
        // Prints the average bytes
        System.out.println(encoder.averageBytesPerChar());
    }
}

输出:

1.0

程序2

// Java program to implement
// the above function
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
  
public class Main {
    public static void main(String[] args) throws Exception
    {
  
        // Gets the new encoder
        CharsetEncoder encoder = Charset.forName("UTF8").newEncoder();
  
        // Prints the average bytes
        System.out.println(encoder.averageBytesPerChar());
    }
}

输出:

1.1

**参考资料: **https://docs.oracle.com/javase/10/docs/api/java/nio/charset/CharsetEncoder.html#averageBytesPerChar()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Java 参考指南