Home  >  Article  >  Java  >  Share three examples of Java string writing to files

Share three examples of Java string writing to files

零下一度
零下一度Original
2017-06-17 11:34:191926browse

This article mainly introduces the relevant information on the implementation of the three ways of writing files in JavaString. Friends in need can refer to the following

Java String Writing Three ways to implement files

1. UseFileWriter


String str="hello world!";
    FileWriter writer;
    try {
      writer = new FileWriter("E:/token.txt");
      writer.write(str);
      writer.flush();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

2. Use FileOutPutStream


##

File txt=new File("E:/log1.txt");
       if(!txt.exists()){ 
         txt.createNewFile(); 
      } 
       byte bytes[]=new byte[512];  
       bytes=str.getBytes(); 
       int b=bytes.length;  //是字节的长度,不是字符串的长度
       FileOutputStream fos=new FileOutputStream(txt); 
       fos.write(bytes,0,b); 
       fos.write(bytes);
       fos.close();

3. Use FileOutPutStream to append to write files


FileOutputStream fos = new FileOutputStream("E:/log.txt",true);
//true表示在文件末尾追加 
fos.write(log.getBytes()); 
fos.close();

The above is the detailed content of Share three examples of Java string writing to files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn