Java FileOutputStream 用于将字节数据写入文件。
如果你需要将原始数据写入文件,就使用FileOutputStream类。
Java.io.FileOutputStream class声明如下:
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.
void write(byte[] ary, int off, int len) 往文件输出流写指定长度字节数组
void write(int b) 往文件输出流写指定字节
void close() 关闭文件输出流
如果你需要将原始数据写入文件,就使用FileOutputStream类。
Java.io.FileOutputStream class声明如下:
public class FileOutputStream extends OutputStream
构造函数
FileOutputStream(File file)Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.
常用函数
void write(byte[] ary) 往文件输出流写指定字节数组void write(byte[] ary, int off, int len) 往文件输出流写指定长度字节数组
void write(int b) 往文件输出流写指定字节
void close() 关闭文件输出流
例子1:
package com.dylan.io;
import java.io.FileOutputStream;
/**
* @author xusucheng
* @create 2017-12-31
**/
public class FileOutputStreamWriteByte {
public static void main(String[] args) {
try {
FileOutputStream fout = new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}
例子2:
package com.dylan.io;
import java.io.FileOutputStream;
/**
* @author xusucheng
* @create 2017-12-31
**/
public class FileOutputStreamWriteString {
public static void main(String[] args) {
try {
FileOutputStream fout = new FileOutputStream("D:\\testout.txt",true);
String s = "Welcome to java.io.";
byte b[] = s.getBytes(); //将字符串转为字节数组
fout.write(b);
fout.close();
System.out.println("写入成功!");
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
测试效果截图:
执行例子1:
执行例子2:
下一章:
Java I/O 教程(四) FileInputStream 类
本文介绍了 Java 中的 FileOutputStream 类,该类用于将字节数据写入文件。文章详细解释了 FileOutputStream 的构造函数,并通过两个实例演示了如何使用该类来写入字节和字符串数据。
2275

被折叠的 条评论
为什么被折叠?



