zoukankan      html  css  js  c++  java
  • java 读取并且显示 txt 文件

    系统:mac os x 10.9

    eclipse

    在eclipse 中建立一个project, 命名为Cin_txt,

    Cin_txt的内容

    test
    wang
    hello
    world

    以下是输入的代码

     

    import java.io.File;
    
    import java.io.FileInputStream;
    
    import java.io.IOException;
    
     
    
    public class Cin_txt {
    
     
    
    public static void main(String[] args) {
    
     
    
    File file = new File("/Users/yinjiewang/Documents/test.txt");
    
    FileInputStream fis = null;
    
     
    
    try {
    
    fis = new FileInputStream(file);
    
     
    
    System.out.println("Total file size to read (in bytes) : "
    
    + fis.available());
    
     
    
    int content;
    
    while ((content = fis.read()) != -1) {
    
    // convert to char and display it
    
    System.out.print((char) content);
    
    }
    
     
    
    } catch (IOException e) {
    
    e.printStackTrace();
    
    } finally {
    
    try {
    
    if (fis != null)
    
    fis.close();
    
    } catch (IOException ex) {
    
    ex.printStackTrace();
    
    }
    
    }
    
    }
    
    }

     JDK7 版本

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
     
    public class ReadFileExample {
     
        public static void main(String[] args) {
     
            File file = new File("C:/robots.txt");
     
            try (FileInputStream fis = new FileInputStream(file)) {
     
                System.out.println("Total file size to read (in bytes) : "+ fis.available());
     
                int content;
                while ((content = fis.read()) != -1) {
                    // convert to char and display it
                    System.out.print((char) content);
                }
     
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    java字符串的遍历以及字符串中各类字符的统计
    Java Jvm运行机制原理
    为什么面试要问 hashmap 的原理
    HashMap的实现原理
    redis两种持久化方式的优缺点
    2018No-java面试知识
    从架构演进的角度聊聊spring cloud都做了些什么?
    MySQL索引优化
    2018java面试知识汇总
    多线程—7种同步方法
  • 原文地址:https://www.cnblogs.com/assassin/p/3726902.html
Copyright © 2011-2022 走看看