zoukankan      html  css  js  c++  java
  • Java基础之写文件——通过缓冲流写文件(StreamOutputToFile)

    控制台程序,生成一些二进制整型值并且将它们写入到文件中。

     1 import java.nio.file.*;
     2 import java.nio.*;
     3 import java.io.*;
     4 
     5 public class StreamOutputToFile {
     6 
     7   public static void main(String[] args) {
     8     final int count = 50;                                              // Number of values
     9     long[] fiboNumbers = {0L,0L};                                      // Array of 2 elements
    10     int index = 0;                                                     // Index to fibonumbers
    11     ByteBuffer buf = ByteBuffer.allocate(count*8);                     // Buffer for output
    12     LongBuffer longBuf = buf.asLongBuffer();                           // View buffer for type long
    13     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("fibonnaci.bin");
    14     try {
    15       // Create parent directory if it doesn't exist
    16       Files.createDirectories(file.getParent());
    17     } catch(IOException e) {
    18       System.err.println("Error creating directory: " + file.getParent());
    19       e.printStackTrace();
    20       System.exit(1);
    21     }
    22 
    23     try(BufferedOutputStream fileOut = new BufferedOutputStream(Files.newOutputStream(file))){
    24       // Generate Fibonacci numbers in buffer
    25       for(int i = 0 ; i < count ; ++i) {
    26         if(i < 2)
    27           fiboNumbers[index] = i;
    28         else
    29           fiboNumbers[index] = fiboNumbers[0] + fiboNumbers[1];
    30         longBuf.put(fiboNumbers[index]);
    31         index = ++index%2;
    32       }
    33     // Write the numbers to the file
    34     fileOut.write(buf.array(), 0, buf.capacity());
    35     System.out.println("File written.");
    36     } catch(IOException e) {
    37       System.err.println("Error writing file: " + file);
    38       e.printStackTrace();
    39     }
    40   }
    41 }
  • 相关阅读:
    软件项目成员的业绩考核
    COM, COM+ and .NET 程序集的区别
    .Net 应用框架设计系列(二)
    怎样在Web开发中完美控制IE标题栏
    影楼系统
    PHP读取ACCESS数据到MYSQL
    简单分享apache 封 IP 的方法
    详解Apache下.htaccess文件常用配置
    fleaphp常用方法分页之Pager
    php遍历文件夹读取文件夹中图片并分页显示图片
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3386714.html
Copyright © 2011-2022 走看看