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

java读取txt文件

2014-01-13 18:52 621 查看
public class TxtReaderTool {
public static final String GBK_ENCODING = "UTF-8";

public static List<String> contentList = new ArrayList<String>();

public static List<String> getContentList() {
return contentList;
}

public static void setContentList(List<String> contentList) {
TxtReaderTool.contentList = contentList;
}

public static void main(String[] args) {
// method 1
// 从当前类路径下获取txt文件
try {
InputStream ips = TxtReaderTool.class.getResourceAsStream("info.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(ips));
String line = null;

while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception");
}

// method 2:
// 从当前的项目路径下获取文件
String filePath = System.getProperty("user.dir") + File.separator + "info.txt";
txtReader(filePath);

for (String t : getContentList()) {
System.out.println(t);
}
}

// 建议采用如此方式
public static void txtReader(String filePath) {
try {
File file = new File(filePath);

InputStreamReader read = new InputStreamReader(new FileInputStream(file), GBK_ENCODING);
BufferedReader br = new BufferedReader(read);

contentList.addAll(IOUtils.readLines(br));
IOUtils.closeQuietly(br);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

// fileReader方式容易出现不好控制缓冲区大小的问题,不建议采用这种方式
public static void txtReaderWithFileReader(String filePath) {
File f = new File(filePath);
char[] ch = new char[1024];
Reader reader = null;
try {
reader = new FileReader(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int count = reader.read(ch);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: