Java OutputStream, PrintWriter 如何写档与输出字串 範例教学与用法

相信各位都有遇过要写档, 或输出字串的情境

OutputStream 与 PrintWriter 可说是最常见的两种方式, 那这两种有何差异呢?

来看两个简单的範例:

首先在C槽底下手动建立一个资料夹 example

public static void main(String[] args) {    String str = "HelloWorld!!";    File file = new File("C:/example/hello.txt);    PrintWriter printWriter = new PrintWriter(file);    printWriter.write(str);    printWriter.close();}

我们可以看到, 在example资料夹底下出现了hello.txt
如果你只是要输出简单的字串, 用PrintWriter是一个很好的选项。

public static void main(String[] args) {    String str = "HelloWorld!!";    File file = new File("C:/example/hello.txt);    FileOutputStream fos = new FileOutputStream(file);    byte[] strToByte = v.getBytes();    fos.write(strToByte);    fos.close();}

聪明的同学可以发现, 第二段程式码跟第一段有些许相似, 只是输出方式不同
OutputStream 把要输出的内容, 转成byte再输出, 在某些情况下非常好用。

出现以下错误, 代表你的C槽底下没有这个资料夹, 故无法建立档案
手动建立一个example资料夹即可。

java.io.FileNotFoundException: C:\example\hello.txt (系统找不到指定的路径。)

那有没有办法用程式自动建立资料夹呢, 当然可以!!
将第二个範例加上简单的几行程式

public static void main(String[] args) {    String str = "HelloWorld!!";    File folder = new File("C:/example");    if(!folder.exists()){        folder.mkdir();  //建立资料夹    }    File file = new File("C:/example/hello.txt");    FileOutputStream fos = new FileOutputStream(file);    byte[] strToByte = v.getBytes();    fos.write(strToByte);    fos.close();}

这里的exists(), 可以判断资料夹是否存在, 存在传回true, 不存在传回false
搭配mkdir(), 就可以建立资料夹了。

如果需要建立大量档案或资料夹, 可以跟for迴圈搭配使用, 有兴趣的朋友们可以练习看看!!
PS.注意档名不要重複了喔


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章