fileoutputstream.write
时间: 2023-06-05 16:47:54 浏览: 72
FileOutputStream.write() 方法用于将给定的字节写入文件输出流。这个方法会将给定的字节写入到文件中,如果文件不存在,会自动创建。如果文件已经存在,写入的内容会覆盖原来的内容。
语法:
public void write(int b) throws IOException
参数:
b - 要写入的字节。
返回值:
此方法没有返回值。
例子:
FileOutputStream fos = new FileOutputStream("test.txt");
fos.write(65);
fos.close();
上面的代码会在当前目录下创建一个名为 "test.txt" 的文件,并将字符'A'的ASCLL码值65写入文件中。
相关问题
FileOutputStream.write(int)怎么用
FileOutputStream.write(int) 方法可以用于将指定的字节(最低字节)写入文件中。该方法的语法如下所示:
void write(int b) throws IOException
其中,b 是要写入文件的字节。如果写入操作成功,则该方法返回的是写入的字节数,否则将抛出 IOException 异常。下面是一个示例代码片段,演示了如何使用 FileOutputStream.write(int) 方法将字节写入文件中:
```
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputDemo {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("test.txt");
int b = 97; // 写入字节的ASCII码
fos.write(b);
fos.close();
System.out.println("写入成功!");
} catch (IOException e) {
System.out.println("写入失败!" + e);
}
}
}
```
上面的代码片段中,首先创建了一个 FileOutputStream 对象,指定要写入的文件名(test.txt)。然后,将字节 97(即字母'a')写入文件中,并且关闭了输出流。最后,输出一条表示写入成功的信息。
FileOutputStream.write在写数据时,什么情况下会阻塞
FileOutputStream.write() 方法是一个阻塞式的 I/O 操作,它会一直等待直到所有数据写入完成。在写入数据时,可能会发生以下情况导致阻塞:
1. 写入数据量较大,超过了操作系统内部缓冲区的大小,此时会阻塞等待内核将数据从用户空间复制到内核空间,然后再将数据写到磁盘上。
2. 写入的目标文件所在的磁盘空间已满,此时会阻塞等待空间释放。
3. 写入过程中出现了 I/O 错误,例如网络断开、磁盘出现坏道等,此时会阻塞等待错误处理完成。
总之,当 FileOutputStream.write() 方法在写入数据时遇到任何一种阻塞情况,它都会一直等待直到阻塞被解除或者抛出异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)