编写一个java程序来读取冗长的字符串(使用流)并将输出写入文件?

时间:2015-09-08 08:29:41

标签: java stream

如何使用流来获取冗长的String作为输入以及如何将输出写入文件?

1 个答案:

答案 0 :(得分:2)

/*

Here is another way you can perform the storage.

* /

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

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

    FileOutputStream fop = null;
    File file;
    String content = "This is the text content";//our you can take it

    try {

        file = new File("c:/newfile.txt");//File creation at C:/
        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);
        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
      }
   finally{
      if(fop!=null){
      fop.flush();
      fop.close();
   }
}