您的位置:首页 > 编程语言 > Java开发

java 读取并且显示 txt 文件

2014-05-14 03:29 627 查看
系统: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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: