zoukankan      html  css  js  c++  java
  • Java基础之读文件——使用输入流读取二进制文件(StreamInputFromFile)

    控制台程序,读取Java基础之读文件部分(StreamOutputToFile)写入的50个fibonacci数字。

     1 import java.nio.file.*;
     2 import java.nio.*;
     3 import java.io.*;
     4 
     5 public class StreamInputFromFile {
     6   public static void main(String[] args) {
     7 
     8     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("fibonnaci.bin");
     9 
    10     if(!Files.exists(file)) {
    11       System.out.println(file + " does not exist. Terminating program.");
    12       System.exit(1);
    13     }
    14 
    15     final int count = 6;                                               // Number of values to be read each time
    16 
    17     // Buffer to hold count values
    18     ByteBuffer buf = ByteBuffer.allocate(8*count);
    19 
    20     LongBuffer values = buf.asLongBuffer();
    21     byte[] bytes = buf.array();                                        // Backing array for buf
    22     int totalRead = 0;                                                 // Total value read
    23     try(BufferedInputStream fileIn = new BufferedInputStream(Files.newInputStream(file))){
    24       int numberRead = 0;
    25       while(true) {
    26         numberRead = fileIn.read(bytes, 0, bytes.length);
    27         if(numberRead == -1)                                           // EOF reached
    28           break;
    29         totalRead += numberRead/8;                                     // Increment total
    30 
    31         for(int i = 0 ; i < numberRead/8 ; ++i)                        // Access as many as there are
    32           System.out.format("%12d", values.get());
    33 
    34         System.out.println();                                          // New line
    35         values.flip();                                                 // Reset for next input
    36       }
    37     System.out.format("%d  values read.%n", totalRead);
    38     } catch(IOException e) {
    39       System.err.println("Error writing file: " + file);
    40       e.printStackTrace();
    41     }
    42   }
    43 }
  • 相关阅读:
    刨析Maven(对pom.xml配置文件常用标签的解析)
    sublime text 3 使用技巧
    CSS3之渐变
    CSS3之过渡
    定位
    Java中的正则表达式
    CSS3之转换
    CSS布局
    导航条菜单制作总结
    Transition
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3387123.html
Copyright © 2011-2022 走看看