相信各位都有遇过要写档, 或输出字串的情境
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.注意档名不要重複了喔