代码之家  ›  专栏  ›  技术社区  ›  Andriy Drozdyuk Pickels

类似Python的Java IO库?

  •  18
  • Andriy Drozdyuk Pickels  · 技术社区  · 14 年前

    Java不是我的主要编程语言,所以我可能会问显而易见的问题。

    但是在Java中是否有一个简单的文件处理库,比如 python ?

    例如,我只想说:

    File f = Open('file.txt', 'w')
    for(String line:f){
          //do something with the line from file
    }
    

    谢谢!

    更新:好吧,StackOverflow自动接受了一个奇怪的答案。这和我的赏金有关-所以如果你想看到其他答案,就向下滚动!

    10 回复  |  直到 14 年前
        1
  •  19
  •   Andriy Drozdyuk Pickels    14 年前

    我想的更多是:

    File f = File.open("C:/Users/File.txt");
    
    for(String s : f){
       System.out.println(s);
    }
    

    这是我的源代码:

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Iterator;
    
    public abstract class File implements Iterable<String>{
        public final static String READ = "r";
        public final static String WRITE = "w";
    
        public static File open(String filepath) throws IOException{
            return open(filepath, READ);
        }   
    
        public static File open(String filepath, String mode) throws IOException{
        if(mode == READ){
            return new ReadableFile(filepath);
        }else if(mode == WRITE){
            return new WritableFile(filepath);
        }
        throw new IllegalArgumentException("Invalid File Write mode '" + mode + "'");
        }
    
        //common methods
        public abstract void close() throws IOException;
    
        // writer specific
        public abstract void write(String s) throws IOException;
    
    }
    
    class WritableFile extends File{
        String filepath;
        Writer writer;
    
        public WritableFile(String filepath){
            this.filepath = filepath;
        }
    
        private Writer writer() throws IOException{
            if(this.writer == null){
                writer = new BufferedWriter(new FileWriter(this.filepath));
            }
            return writer;
        }
    
        public void write(String chars) throws IOException{
            writer().write(chars);
        }
    
        public void close() throws IOException{
            writer().close();
        }
    
        @Override
        public Iterator<String> iterator() {        
            return null;
        }
    }
    
    class ReadableFile extends File implements Iterator<String>{
        private BufferedReader reader;
        private String line;    
        private String read_ahead;
    
        public ReadableFile(String filepath) throws IOException{        
            this.reader = new BufferedReader(new FileReader(filepath)); 
            this.read_ahead = this.reader.readLine();
        }
    
        private Reader reader() throws IOException{
             if(reader == null){
                   reader = new BufferedReader(new FileReader(filepath));   
             }
             return reader;
        }
    
        @Override
        public Iterator<String> iterator() {
            return this;
        }
    
        @Override
        public void close() throws IOException {
            reader().close();
        }
    
        @Override
        public void write(String s) throws IOException {
            throw new IOException("Cannot write to a read-only file.");
        }
    
        @Override
        public boolean hasNext() {      
            return this.read_ahead != null;
        }
    
        @Override
        public String next() {
            if(read_ahead == null)
                line = null;
            else
                line = new String(this.read_ahead);
    
            try {
                read_ahead = this.reader.readLine();
            } catch (IOException e) {
                read_ahead = null;
                reader.close()
            }
            return line;
        }
    
        @Override
        public void remove() {
            // do nothing       
        }
    }
    

    下面是它的单元测试:

    import java.io.IOException;
    import org.junit.Test;
    
    public class FileTest {
        @Test
        public void testFile(){
            File f;
            try {
                f = File.open("File.java");
                for(String s : f){
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Test
        public void testReadAndWriteFile(){
            File from;
            File to;
            try {
                from = File.open("File.java");
                to = File.open("Out.txt", "w");
                for(String s : from){           
                    to.write(s + System.getProperty("line.separator"));
                }
                to.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }   
        }
    }
    
        2
  •  11
  •   Jesper    14 年前

    在爪哇逐行读取文件:

    BufferedReader in = new BufferedReader(new FileReader("myfile.txt"));
    
    String line;
    while ((line = in.readLine()) != null) {
        // Do something with this line
        System.out.println(line);
    }
    
    in.close();
    

    I/O的大多数类都在包中 java.io . 请参阅该包的API文档。看一看 Sun's Java I/O tutorial 更多详细信息。

    附加 :上面的示例将使用系统的默认字符编码来读取文本文件。如果要显式指定字符编码,例如utf-8,请将第一行更改为:

    BufferedReader in = new BufferedReader(
        new InputStreamReader(new FileInputStream("myfile.txt"), "UTF-8"));
    
        3
  •  4
  •   stacker    14 年前

    如果您已经对 Apache commons lang commons io 这可能是另一种选择:

    String[] lines = StringUtils.split(FileUtils.readFileToString(new File("myfile.txt")), '\n');
    for(String line: lines){
          //do something with the line from file
    }
    

    (我更喜欢杰斯帕的回答)

        4
  •  4
  •   Grantismo    14 年前

    如果要按字符串迭代文件,可能会发现有用的类是 扫描仪 班级。

    import java.io.*;
    import java.util.Scanner;
    
        public class ScanXan {
            public static void main(String[] args) throws IOException {
                Scanner s = null;
                try {
                    s = new Scanner(new BufferedReader(new FileReader("myFile.txt")));
    
                    while (s.hasNextLine()) {
                        System.out.println(s.nextLine());
                    }
                } finally {
                    if (s != null) {
                        s.close();
                    }
                }
            }
        }
    

    API非常有用: http://java.sun.com/javase/7/docs/api/java/util/Scanner.html 还可以使用正则表达式解析文件。

        5
  •  3
  •   Cowan    14 年前

    我从不厌倦给谷歌拉皮条 guava-libraries 这可以减轻很多痛苦…好吧,大部分的东西都在Java中。

    怎么样:

    for (String line : Files.readLines(new File("file.txt"), Charsets.UTF_8)) {
       // Do something
    }
    

    如果您有一个大文件,并且想要一个逐行回调(而不是将整个文件读取到内存中),您可以使用 LineProcessor 这增加了一些样板(由于缺少闭包…叹息)但是仍然保护你不去处理阅读本身,以及所有相关的 Exceptions :

    int matching = Files.readLines(new File("file.txt"), Charsets.UTF_8, new LineProcessor<Integer>(){
      int count;
    
      Integer getResult() {return count;}
    
      boolean processLine(String line) {
         if (line.equals("foo")
             count++;
         return true;
      }
    });
    

    如果您实际上不希望结果从处理器中返回,并且从不过早中止(布尔值返回的原因 processLine 你可以 然后 做一些类似的事情:

    class SimpleLineCallback extends LineProcessor<Void> {
        Void getResult{ return null; }
    
        boolean processLine(String line) {
           doProcess(line);
           return true;
        }
    
        abstract void doProcess(String line);
    }
    

    然后你的代码可能是:

    Files.readLines(new File("file.txt"), Charsets.UTF_8, new SimpleLineProcessor(){
      void doProcess(String line) {
         if (line.equals("foo");
             throw new FooException("File shouldn't contain 'foo'!");
      }
    });
    

    相应地更干净。

        6
  •  2
  •   McDowell rahul gupta    14 年前
      public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("scan.txt"));
        try {
          while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
          }
        } finally {
          scanner.close();
        }
      }
    

    一些注意事项:

        7
  •  1
  •   Pascal Thivent    14 年前

    使用简单示例 Files.readLines() 从番石榴IO LineProcessor 回调:

    import java.io.File;
    import java.io.IOException;
    
    import com.google.common.base.Charsets;
    import com.google.common.io.Files;
    import com.google.common.io.LineProcessor;
    
    public class GuavaIoDemo {
    
        public static void main(String[] args) throws Exception {
            int result = Files.readLines(new File("/home/pascal/.vimrc"), //
                Charsets.UTF_8, // 
                new LineProcessor<Integer>() {
                    int counter;
    
                    public Integer getResult() {
                        return counter;
                    }
    
                    public boolean processLine(String line) throws IOException {
                        counter++;
                        System.out.println(line);
                        return true;
                    }
                });
        }
    }
    
        8
  •  0
  •   Nathan Voxland    14 年前

    你可以使用 jython 它允许您在Java中运行Python语法。

        9
  •  0
  •   Goibniu    14 年前

    这里有一个很好的例子: Line by line iteration

        10
  •  0
  •   James Anderson    14 年前

    试试看groovy!

    它是在JVM中运行的Java的超集。最有效的Java代码也是有效的Groovy,因此您可以直接访问任何百万个Java API。

    除此之外,它还有许多为蟒蛇所熟悉的更高级的结构,还有 许多扩展可以减轻映射、列表、SQL、XML的痛苦,您猜对了——文件IO。