c语言sscanf函数的用法是什么
238
2023-07-22
Java中FileOutputStream流的write方法
本文为大家分享了FileOutputStream流的write方法,供大家参考,具体内容如下
/*------------------------
FileOutputStream:
....//输出流,字节流
....//write(byte[] b)方法: 将b.length个字节从指定字节数组写入此文件输出流中
....//write(byte[] b, int off, int len)方法:将指定字节数组中从偏移量off开始的len个字节写入此文件输出流
-------------------------*/
package pack02;
import java.io.*;
public class Demo {
public static void main(String[] args) {
testMethod1(); //从程序中向一个文件写入数据
testMethRtHrcoQUTod2(); //复制一个文件的内容到另一个文件
}
//从程序中向一个文件写入数据
public static void testMethod1() {
File file1 = new File("d:/TEST/MyFile1.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1); //将FileOutputStream流对象连接到file1代表的文件
fos.write( new String("This is MyFile1.txt").getBytes() );
//使用方法write(byte[] b),即向文件写入一个byte数组的内容
//这里创建一个字符串对象,并调用方法getBytes(),将其转换成一个字符数组作为write(byte[] b)的形参
//当文件MyFile1.txt不存在时,该方法会自动创建一个这个文件RtHrcoQUT;当文件已经存在时,该方法会创建一个新的同名文件进行覆盖并写入数组内容
} catch (IOException e) {
e.printStackTrace();
} finally {
if( fos != null )
try {
fos.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
//从一个文件读取数据,然后写入到另一个文件中;相当于内容的复制
public static void testMethod2() {
File fileIN = new File("d:/TEST/MyFile2.txt"); //定义输入文件
File fileOUT = new File("d:/TEST/MyFile3.txt"); //定义输出文件
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(fileIN); //输入流连接到输入文件
fos = new FileOutputStream(fileOUT); //输出流连接到输出文件
byte[] arr = new byte[10]; //该数组用来存入从输入文件中读取到的数据
int len; //变量len用来存储每次读取数据后的返回值
while( ( len=fis.read(arr) ) != -1 ) {
fos.write(arr, 0, len);
}//while循环:每次从输入文件读取数据后,都写入到输出文件中
} catch (IOException e) {
e.printStackTrace();
}
//关闭流
try {
fis.close();
RtHrcoQUT fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注:希望与各位读者相互交流,共同学习进步。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~