zoukankan      html  css  js  c++  java
  • Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)

    控制台程序,将一列字符串写入到文件中。

     1 import java.io.*;
     2 import java.nio.file.*;
     3 import java.nio.charset.Charset;
     4 
     5 public class WriterOutputToFile {
     6   public static void main(String[] args) {
     7     String[] sayings = {"A nod is as good as a wink to a blind horse.",
     8                         "Least said, soonest mended.",
     9                         "There are 10 kinds of people in the world, " +
    10                         "those that understand binary and those that don't.",
    11                         "You can't make a silk purse out of a sow's ear.",
    12                         "Hindsight is always twenty-twenty.",
    13                         "Existentialism has no future.",
    14                         "Those who are not confused are misinformed.",
    15                         "Better untaught that ill-taught."};
    16 
    17     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Sayings.txt");
    18     try {
    19       // Create parent directory if it doesn't exist
    20       Files.createDirectories(file.getParent());
    21     } catch(IOException e) {
    22       System.err.println("Error creating directory: " + file.getParent());
    23       e.printStackTrace();
    24       System.exit(1);
    25     }
    26     try(BufferedWriter fileOut = Files.newBufferedWriter(
    27                                       file, Charset.forName("UTF-16"))){
    28       // Write saying to the file
    29       for(int i = 0 ; i < sayings.length ; ++i) {
    30         fileOut.write(sayings[i], 0, sayings[i].length());
    31         fileOut.newLine();                                             // Write separator
    32       }
    33     System.out.println("File written.");
    34     } catch(IOException e) {
    35       System.err.println("Error writing file: " + file);
    36       e.printStackTrace();
    37     }
    38   }
    39 }
  • 相关阅读:
    js静态成员和实例成员
    js构造函数
    js创建对象
    js演示面向对象
    JavaScript特点
    像素鸟游戏
    图片瀑布流
    微信聊天模拟
    飞机游戏动画特效
    SpringBoot 核心理论
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3386717.html
Copyright © 2011-2022 走看看