int n = 0 ; while((n = reader.read()) != -1){ System.out.print((char)n);
时间: 2024-04-19 09:27:44 浏览: 18
这段代码使用 while 循环来读取文件中的数据,并将其以字符形式打印出来。循环中,`reader.read()` 方法会返回下一个字符的 ASCII 值,赋值给变量 n。如果读取到文件末尾,则 `reader.read()` 方法会返回 -1,循环结束。然后,使用 `(char)n` 将 ASCII 值转换为对应的字符,并使用 `System.out.print()` 方法打印出来。这样,文件中的内容就会被逐个字符地输出到控制台上。
相关问题
char[] ch = new char[4]; int num = 0; while((num = reader.read(ch)) != -1){ System.out.print(new String(ch,0,num));
这段代码创建了一个长度为4的字符数组 ch,用于存储从文件中读取的字符数据。变量 num 用于记录实际读取到的字符数。
在 while 循环中,`reader.read(ch)` 方法会尝试将字符数据读取到数组 ch 中,并返回实际读取到的字符数。如果读取到文件末尾,则 `reader.read(ch)` 方法会返回 -1,循环结束。
然后,通过 `new String(ch, 0, num)` 将字符数组中的字符转换为字符串,并使用 `System.out.print()` 方法打印出来。这样,文件中的内容会被以每次读取 4 个字符的方式输出到控制台上。
1、阅读下面程序,叙述其功能 import java.io.FileReader; import java.io.IOException; public class FileViewer { /** Defines the entry point of the program. */ public static void main(String[] args) { System.out.println("Please enter the file path:"); try { String fileName = ""; while(true) { int readByte = System.in.read(); if(readByte == -1 || readByte == '\n') break; fileName += (char) readByte; } // Reads the file and prints it to the System.out stream. char[] buffer = new char[20]; FileReader reader = new FileReader(fileName); while(true) { int length = reader.read(buffer); if(length < 0) // Reads a long as there is more data. break; String text = new String(buffer, 0, length); System.out.print(text); } } catch (IOException e) { e.printStackTrace(); } } }
这段程序的功能是接收用户输入的文件路径,然后读取该文件并将其内容输出到标准输出流(System.out)中。程序使用 FileReader 类来读取文件。程序首先提示用户输入文件路径,然后通过 System.in.read() 方法一次读取一个字节,直到读取到回车符为止。然后程序使用 FileReader 类读取文件,并将每次读取到的内容存储到一个字符数组中,最后将字符数组转换为字符串并输出。如果读取到文件末尾,程序会结束。如果读取文件时发生了 IOException 异常,程序会打印出异常信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)