zoukankan      html  css  js  c++  java
  • Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)

    控制台程序,将一系列有用的格言写入到文件中。

    本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前字符串中存在的字符数目,也可以使用视图缓冲区来读取字符串。

     1 import static java.nio.file.StandardOpenOption.*;
     2 import java.nio.file.*;
     3 import java.nio.channels.*;
     4 
     5 import java.util.EnumSet;
     6 import java.io.IOException;
     7 import java.nio.ByteBuffer;
     8 
     9 public class WriteProverbs {
    10   public static void main(String[] args) {
    11     String[] sayings = {
    12       "Indecision maximizes flexibility.",
    13       "Only the mediocre are always at their best.",
    14       "A little knowledge is a dangerous thing.",
    15       "Many a mickle makes a muckle.",
    16       "Who begins too much achieves little.",
    17       "Who knows most says least.",
    18       "A wise man sits on the hole in his carpet."
    19     };
    20 
    21     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Proverbs.txt");// Path object for the file
    22     try {
    23       Files.createDirectories(file.getParent());                       // Make sure we have the directory
    24     } catch (IOException e) {
    25       e.printStackTrace();
    26       System.exit(1);
    27     }
    28 
    29     // The buffer must accommodate the longest string
    30     // so we find the length of the longest string
    31     int maxLength = 0;
    32     for (String saying : sayings) {
    33       if(maxLength < saying.length())
    34         maxLength = saying.length();
    35     }
    36     // The buffer length must hold the longest string
    37     // plus its length as a binary integer
    38     // Each character needs 2 bytes and an integer 4 bytes
    39     ByteBuffer buf = ByteBuffer.allocate(2*maxLength + 4);
    40 
    41     try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))) {
    42 
    43      for (String saying : sayings) {
    44         buf.putInt(saying.length()).asCharBuffer().put(saying);
    45         buf.position(buf.position() + 2*saying.length()).flip();
    46         channel.write(buf);                                            // Write the buffer to the file channel
    47         buf.clear();
    48       }
    49       System.out.println("Proverbs written to file.");
    50     } catch (IOException e) {
    51       e.printStackTrace();
    52     }
    53   }
    54 }
  • 相关阅读:
    初识spring
    关于导入别人的web项目,tomcat无法显示的问题
    doPost无法跳转显示信息,只能下载文件查看
    socket网络编程
    log日志文件
    第三方模块安装
    __name__ __doc__ __package__
    格式化
    导入模块
    python正则表达式补充
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3386730.html
Copyright © 2011-2022 走看看