java怎么把文本内容在指定文件夹里

如题所述

java写入文件到指定文件夹的方法主要有两种:利用PrintStream和利用StringBuffer


例如将文本“I'm the text to be write”写入到文件夹D:/test下,并命名为test.txt,则两种方式简单实现代码如下:


1. 利用PrintStream写文件

    public void PrintStreamDemo(){
         try {
             FileOutputStream out=new FileOutputStream("D:/test.txt");
             PrintStream p=new PrintStream(out);
             p.println("I'm the text to be write");
         } catch (FileNotFoundException e){
             e.printStackTrace();
         }
     }


2. 利用StringBuffer写文件

    public void StringBufferDemo() throws IOException{
         File file=new File("D:/test.txt");
         if(!file.exists())
             file.createNewFile();
         FileOutputStream out=new FileOutputStream(file,true);
             StringBuffer sb=new StringBuffer();
             sb.append("I'm the text to be write");
             out.write(sb.toString().getBytes("utf-8"));
         }        
         out.close();
     }

提示:利用StringBuffer写文件可以设定使用何种编码,有效解决中文问题。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-22
FileWriter 的write(String str)即可,注意如果你不想覆盖之前的内容,这个
FileWriter fw = new FileWriter(File file,boolean append),这里的append 应赋上true
而且因为字符流都是使用了缓冲区的,所以记得flush或close本回答被提问者采纳
第2个回答  2016-04-17
io流,好简单,你百度下就出来好多

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网