【问题标题】:Please help me understand the following java code请帮我理解下面的java代码
【发布时间】:2012-02-03 19:58:39
【问题描述】:

我正在从 Java 学习 java:完整参考。 我目前正在研究本章中的示例:输入/输出:探索 java.io 我从下面的示例中理解了几行代码。 谁能帮我举个例子。

import java.io.*;

class FileInputStreamDemo
{
public static void main(String args[]) throws IOException
{
InputStream f = new FileInputStream("E://SomeRandomTextFile.txt");
System.out.println("Total available bytes : " + size = f.available());

int n = size/40;
System.out.println("First" + n + " bytes of file one read() at a time");

for(int i=0; i<n; i++)
{
System.out.println((char) f.read());
}

System.out.println("\n Still available: "+ f.available());
System.out.println("Reading the text " + n + " with one read(b[])");
byte b[] = new byte[n];

if(f.read(b) != n)
{
System.err.println("coudn't read" + n + "bytes.");
}
System.out.println(new String(b,0,n));
}

在上面的代码中,我勉强看懂了最后五行代码。

结果是什么

f.read(b) 

什么是

System.err

结果是什么

new String(b,0,n);

【问题讨论】:

    标签: java input io


    【解决方案1】:

    应该是:

    if(f.read(b) != n)
    

    这是一个将文件中的字节读入缓冲区的方法调用。来自 javadoc:

    从输入流中读取一些字节并将它们存储到 缓冲区数组 b。

    这一行:

    new String(b,0,n);
    

    从缓冲区b 中的字节创建一个新的String,从索引0 开始并获取接下来的n 个字节。来自 javadoc:

    通过解码指定的字节子数组构造一个新的字符串 使用平台的默认字符集。

    最后是这个:

    System.err
    

    返回对程序标准错误流的引用。

    【讨论】:

    • 已编辑。感谢您的回答。您的回答非常有帮助。
    【解决方案2】:

    f.read(b) 生成长度为 1 的整数或单个字节。

    System.err 定位错误窗口,然后在其中放置一条消息,就像System.out 定位控制台窗口然后在那里放置一条消息一样。

    new String(b,0,n) 将使用 String(byte[] bytes, int offset, int length) 构造函数以字节数组 b 创建一个字符串,从偏移量 0 开始,长度为 n。

    【讨论】:

    • 好吧,这里我们有read(byte[]),它用于读取一些字节数来缓冲。它返回读取的字节数,如果我们有 EOF 或其他流没有返回数据的东西,则返回 -1。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2014-01-15
    • 2020-04-11
    • 1970-01-01
    • 2022-11-21
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多