目录
FileOutputStream类
这个函数还可以加个参数true/false
给出源码:
package ljy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hellojave {
public static void main(String[] args) {
File f= new File("word.txt");
FileOutputStream out=null;
try {
out=new FileOutputStream(f,false);//覆盖原有内容
String str="刘家奕是南昌航空大学第一好帅";
byte b[]=str.getBytes();//字符串转换为字节数组
out.write(b);//将字节数组写入到文档中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
FileInputStream类
代码为下半段
package ljy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hellojave {
public static void main(String[] args) {
File f= new File("word.txt");
FileOutputStream out=null;
try {
out=new FileOutputStream(f,false);//覆盖原有内容
String str="刘家奕是南昌航空大学第一好帅";
byte b[]=str.getBytes();//字符串转换为字节数组
out.write(b);//将字节数组写入到文档中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
FileInputStream in=null;
try {
in=new FileInputStream(f);//输入流读文件
byte b2[]=new byte[1024];//缓冲区
int len=in.read(b2);
System.out.println("文件中的内容为:"+new String(b2,0,len));
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
主要代码为: