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(); } } }
相关文章推荐
- Java读取txt文件的方法
- JAVA 创建TXT文件,写入文件内容,读取文件内容
- java实现读取txt文件并以在每行以空格取数据
- JAVA 创建TXT文件,写入文件内容,读取文件内容
- Java中从txt文件中读取和存储内容出现乱码的解决之道一:
- java代码读取port.txt文件的代码
- Java中从txt文件中读取和存储内容出现乱码的解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”的解决方案
- Java如何读取数据文件,如txt文件或者.dat文件 中的内容
- Java 读取TXT文件的多种方式
- java中读取txt文件获得编码格式方法
- java读取UTF-8的txt文件发现开头的一个字符问题
- Java写入TXT文件和读取
- Java读取txt文件,计算2011年9月份的通话时间
- java对.txt文件进行读取方法实战---室友是网络安全方向,帮他提取文件里的特定ip
- java 读取,写入 txt 文件示例
- java读取txt文件并以在每行以空格取数据
- java读取txt文件中的数据
- JAVA 读取txt文件内容
- JAVA 创建TXT文件,写入文件内容,读取文件内容