public class FileOutputStreamTest {
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>// TODO Auto-generated method stub
<span style="white-space:pre"> </span>new FileOutputStreamTest().writerByByte("abcd", "d:\\JAVA之路.txt");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//将字符串与入输出流中
<span style="white-space:pre"> </span>public void writerByByte(String source,String filePath){
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>File file = new File(filePath);
<span style="white-space:pre"> </span>FileOutputStream fos = null;
<span style="white-space:pre"> </span>byte[] buf = source.getBytes();
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>fos = new FileOutputStream(file,true);//true是默认是添加到文件尾部
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//一次写入一个字节
<span style="white-space:pre"> </span>for (int i = 0; i < buf.length; i++) {
<span style="white-space:pre"> </span>fos.write(buf[i]);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>//一次写入字节数组
<span style="white-space:pre"> </span>//fos.write(buf);
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>} catch (FileNotFoundException e) {
<span style="white-space:pre"> </span>// TODO Auto-generated catch block
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>} catch (IOException e) {
<span style="white-space:pre"> </span>// TODO Auto-generated catch block
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>} finally{
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>fos.close();
<span style="white-space:pre"> </span>} catch (IOException e) {
<span style="white-space:pre"> </span>// TODO Auto-generated catch block
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}
学习笔记 - FileOutputStream流将字符串写入文件中
最新推荐文章于 2024-06-29 11:42:01 发布