zoukankan      html  css  js  c++  java
  • 可以直接用的文件读取类

    1.这个类可以直接使用

    //: net/mindview/util/TextFile.java
    // Static functions for reading and writing text files as
    // a single string, and treating a file as an ArrayList.
    package com.feilong.reptile.util;
    import java.io.*;
    import java.util.*;
    
    public class TextFile extends ArrayList<String> {
      // Read a file as a single string:
      // 这里的fileName 要用全路经,带文件名的那种。 public static String read(String fileName) { StringBuilder sb = new StringBuilder(); try { BufferedReader in= new BufferedReader(new FileReader( new File(fileName).getAbsoluteFile())); try { String s; while((s = in.readLine()) != null) { sb.append(s); sb.append(" "); } } finally { in.close(); } } catch(IOException e) { throw new RuntimeException(e); } return sb.toString(); } // Write a single file in one method call: public static void write(String fileName, String text) { try { PrintWriter out = new PrintWriter( new File(fileName).getAbsoluteFile()); try { out.print(text); } finally { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } } // Read a file, split by any regular expression: public TextFile(String fileName, String splitter) { super(Arrays.asList(read(fileName).split(splitter))); // Regular expression split() often leaves an empty // String at the first position: if(get(0).equals("")) remove(0); } // Normally read by lines: public TextFile(String fileName) { this(fileName, " "); } public void write(String fileName) { try { PrintWriter out = new PrintWriter( new File(fileName).getAbsoluteFile()); try { for(String item : this) out.println(item); } finally { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } } // Simple test: public static void main(String[] args) { String file = read("TextFile.java"); write("test.txt", file); TextFile text = new TextFile("test.txt"); text.write("test2.txt"); // Break into unique sorted list of words: TreeSet<String> words = new TreeSet<String>( new TextFile("TextFile.java", "\W+")); // Display the capitalized words: System.out.println(words.headSet("a")); } } /* Output: [0, ArrayList, Arrays, Break, BufferedReader, BufferedWriter, Clean, Display, File, FileReader, FileWriter, IOException, Normally, Output, PrintWriter, Read, Regular, RuntimeException, Simple, Static, String, StringBuilder, System, TextFile, Tools, TreeSet, W, Write] *///:~
  • 相关阅读:
    安装GitLab出现ruby_block[supervise_redis_sleep] action run
    docker tag根据镜像id做标签,用于应用的回滚
    Jenkenis报错:该jenkins实例似乎已离线
    kubernetes-批量删除Evicted Pods
    阿里云k8s构建镜像时设置版本号用于版本回滚
    Java虚拟机6:内存溢出和内存泄露、并行和并发、Minor GC和Full GC、Client模式和Server模式的区别
    Java虚拟机5:Java垃圾回收(GC)机制详解
    Java虚拟机4:内存溢出
    Java虚拟机3:常用JVM命令参数
    Java虚拟机2:Java内存区域及对象
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11134657.html
Copyright © 2011-2022 走看看