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 }
原文地址:https://www.cnblogs.com/mannixiang/p/3386714.html