java - 我是 Java 新手, while(t!=-1) [READFILE] 意味着什么?

标签 java readfile

我是 Java 新手,正在学习如何从 .t​​xt 读取文件。我在讲座中偶然发现了许多笔记,我只是想知道当我尝试从我的小而简单的 java 代码中读取文件时为什么必须是 while(t!=-1) 。

感谢您的回答。 :)

编辑:谢谢你们的回答。我知道-1意味着文件结束,因此循环将继续,直到文件被完全读取。但它必须是-1吗?这是Java中的某种特定规则吗?谢谢。

import java.io.*;
public class test2 {
public static void main(String[] args) throws Exception{
FileReader inone = new FileReader("myfile.txt");
int t=inone.read();
while (t!=-1) {
    System.out.print((char)t);
    t=inone.read();
    }
  }
}

最佳答案

我猜你正在谈论读取文件内容的循环。

通常看起来像:

while (int symbol = inputStreamRef.read()!=-1) {
   // do something
}

inputStreamRefInputStream子类对象。

inputStreamRef.read() - 读取文件,并在到达文件末尾时返回-1

while (symbol != -1) 表示尚未到达文件末尾,我们需要继续读取文件内容。

<小时/> 更新

根据您发布的代码,查看我的评论:

// you are initializing the reader for the file
FileReader inone = new FileReader("myfile.txt");

// reading the first byte to the 't' variable
int t=inone.read();

// if file is empty, 't' will contain -1
// and loop won't start
while (t!=-1) {
   // if t does not contain -1, then end of file is not reached
   // printing byte
   System.out.print((char)t);

   // reading the next byte
   t=inone.read();
}

关于java - 我是 Java 新手, while(t!=-1) [READFILE] 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36712176/

相关文章:

java - 如何从 spring-boot 执行 postgres sql block

java - 如何使用Selenium和Java从html中提取文本2?

java - 获取从运行可运行对象的线程创建可运行对象的方法

无法将 ‘char (*)[1024]’ 转换为 ‘char*’ 作为返回

c - 如何使用双指针从文本文件填充字符串数组?

java - Libgdx - 触摸按钮时如何退出应用程序?

python - 在 Python 中打开 .log 扩展名文件

c - 从文件读取并使用 strtok while 循环仅打印每行的第一个单词

c# - 在 C# 中读取特定编码类型的 .txt 文件

java - Hibernate、Spring 和 HSQL : Table not Found Exception