3.编程用字节流实现从键盘输入以“?”结束的一串字符, 然后将该串中“?”前面 的所有字符顺序写入磁盘文件d:dosInewFile txt
时间: 2024-02-22 11:00:35 浏览: 17
好的,以下是一个 Java 程序示例,用于实现从键盘输入以“?”结束的一串字符,然后将该串中“?”前面的所有字符顺序写入磁盘文件`d:\dosInewFile.txt`:
```java
import java.io.*;
public class ByteStreamDemo {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
FileOutputStream out = new FileOutputStream("d:\\dosInewFile.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, 0, len);
int index = str.indexOf('?');
if (index != -1) {
out.write(str.substring(0, index).getBytes());
break;
} else {
out.write(buffer, 0, len);
}
}
in.close();
out.close();
}
}
```
程序首先使用 System.in 获取标准输入流,然后创建一个 FileOutputStream 对象,用于将读取的数据写入到文件中。在主循环中,程序不断调用 read() 方法读取输入流中的数据,将读取到的字节存储到 buffer 中,并将其转换为字符串。
接下来,程序在读取到的字符串中查找“?”字符。如果找到了“?”字符,则截取该字符前面的所有字符并写入到文件中,然后退出循环;否则,将整个字符串写入到文件中。最后,程序关闭输入流和输出流。
需要注意的是,程序中使用了字节流来读取和写入文件,因此在读取和写入时需要进行字符编码的转换。在本程序中,我们使用了默认的字符编码,即 UTF-8。