发布于 2016-07-11 12:55:46 | 209 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Java函数式编程,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


这篇文章主要介绍了java文件输出流写文件的几种方法,需要的朋友可以参考下

java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。


package com.yiibai.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
 public static void main(String[] args) {

  FileOutputStream fop = null;
  File file;
  String content = "This is the text content";

  try {

   file = new File("c:/newfile.txt");
   fop = new FileOutputStream(file);

   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}
//更新的JDK7例如,使用新的“尝试资源关闭”的方法来轻松处理文件。
package com.yiibai.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
 public static void main(String[] args) {

  File file = new File("c:/newfile.txt");
  String content = "This is the text content";

  try (FileOutputStream fop = new FileOutputStream(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务