Java基础之写文件——创建通道并且写文件(TryChannel)

控制台程序,创建一个文件并且使用通道将一些文本写入到这个文件中。

 1 import static java.nio.file.StandardOpenOption.*;
 2 import java.nio.channels.WritableByteChannel;
 3 import java.io.IOException;
 4 import java.nio.ByteBuffer;
 5 import java.util.EnumSet;
 6 import java.nio.file.*;
 7 
 8 public class TryChannel {
 9 
10   public static void main(String[] args) {
11     String[] sayings = {"The more you plan the luckier you get.",
12                         "The time to complete a project is the time one person would need to complete it " +
13                         "multiplied by the number of people on the project.",
14                         "If at first you don't succeed, remove any evidence that you tried.",
15                         "A clever person solves problems, a wise person avoids them.",
16                         "Death is nature's way of telling you to slow down.",
17                         "A hen is an egg's way of making other eggs.",
18                         "The earlier you begin coding the later you finish.",
19                         "Anything you can't understand is intuitively obvious."};
20 
21     String separator = System.lineSeparator();
22 
23     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("MoreSaying.txt");             // The file path
24     try {
25       // Create parent directory if it doesn't exist
26       Files.createDirectories(file.getParent());
27     } catch(IOException e) {
28       System.err.println("Error creating directory: " + file.getParent());
29       e.printStackTrace();
30       System.exit(1);
31     }
32     System.out.println("New file is: " + file);
33     ByteBuffer buf = null;                                           // Buffer to hold a saying
34     try(WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(CREATE, WRITE))){
35 
36       // Write sayings to the file
37       for(String saying : sayings) {
38         buf = ByteBuffer.wrap((saying + separator).getBytes());  // Saying & separator in buffer
39         channel.write(buf);
40       }
41       System.out.println("File written.");
42     } catch (IOException e) {
43       e.printStackTrace();
44     }
45   }
46 }

 

转载于:https://www.cnblogs.com/mannixiang/p/3386719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值