java 读取并且显示 txt 文件

时间:2023-03-09 08:33:25
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();
}
}
}