怎样在这段代码中手动指定读取和写入的字节数?
时间: 2023-04-04 09:00:34 浏览: 65
您可以使用read()和write()函数来手动指定读取和写入的字节数。在read()函数中,第二个参数指定要读取的字节数,而在write()函数中,第三个参数指定要写入的字节数。例如,以下代码将从文件中读取10个字节并将其写入另一个文件中:
char buffer[10];
int bytesRead = read(file1, buffer, 10);
int bytesWritten = write(file2, buffer, bytesRead);
相关问题
2.利用字节输入输出流,往D盘下的“Test.txt”文件写入一段英文,并读取出来显示在Java的Control控制台中。
以下是示例代码:
```java
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try {
// 写入文件
OutputStream os = new FileOutputStream("D:/Test.txt");
String content = "Hello world!";
os.write(content.getBytes());
os.close();
// 读取文件
InputStream is = new FileInputStream("D:/Test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// 输出到控制台
System.out.println(new String(buffer));
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码首先使用 `OutputStream` 将字符串写入到文件中,然后使用 `InputStream` 读取文件内容,并将读取到的字节转换为字符串输出到控制台中。注意,在使用 `OutputStream` 和 `InputStream` 时需要手动关闭流。
使用FileInputStream字节流读取文件中数据在项目目录下创建一个文本文件fis.txt,在文件中编辑内容“Welcome to learn IO stream!”。在项目中创建一个名称为Example01的类。在main()方法中,通过FileInputStream(String name)构造方法创建文件输入字节流对象,并指定待读取文件fis.txt的路径。把fis.txt文件的内容读出来显示在控制台,关闭流。 在main()方法中,通过FileOutputStream(String name)构造方法创建文件输出字节流对象,并指定写入的文件路径为文本文件fis.txt。定义一段字符串,并将它转换成byte数组,然后通过write(byte[] b)方法,将byte数组写入到文件输出流中。关闭流资源
好的,这个问题和上一个问题基本一致。以下是示例代码:
```java
import java.io.*;
public class Example01 {
public static void main(String[] args) {
// 读取文件内容
try (FileInputStream fis = new FileInputStream("fis.txt")) {
byte[] content = new byte[fis.available()];
fis.read(content);
System.out.println(new String(content));
} catch (IOException e) {
e.printStackTrace();
}
// 写入文件内容
try (FileOutputStream fos = new FileOutputStream("fis.txt")) {
String str = "Hello, world!";
byte[] bytes = str.getBytes();
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意,这里同样使用了 try-with-resources 语句,可以自动关闭流资源,无需手动调用 close() 方法。在读取文件内容时,我们使用 `fis.available()` 方法获取文件的可读字节数,并将其作为数组长度创建 byte 数组,从而一次性读取整个文件内容。在写入文件内容时,我们先定义了一个字符串,然后使用 `getBytes()` 方法将其转换为 byte 数组,最后通过 `fos.write(bytes)` 方法写入到文件输出流中。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)