类似python的Java IO库?

时间:2010-05-10 12:55:00

标签: java python file-io

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

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

例如我只想说:

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

谢谢!

更新:好吧,stackoverflow自动接受了一个奇怪的答案。它与我放置的赏金有关 - 所以如果你想看到其他答案,只需向下滚动!

10 个答案:

答案 0 :(得分:19)

我正在考虑更多的事情:

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();
        }   
    }
}

答案 1 :(得分:11)

在Java中逐行读取文件:

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"));

答案 2 :(得分:4)

如果您已经与Apache commons langcommons io有依赖关系,那么这可能是另一种选择:

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

(我更喜欢Jesper的回答)

答案 3 :(得分:4)

如果您想通过字符串迭代文件,您可能会发现有用的类是 Scanner 类。

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 您也可以使用正则表达式解析文件。

答案 4 :(得分:3)

我从不厌倦拉皮条的谷歌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'!");
  }
});

相应更干净。

答案 5 :(得分:2)

  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();
    }
  }

一些警告:

答案 6 :(得分:1)

使用来自guava-io的Files.readLines()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;
                }
            });
    }
}

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

答案 9 :(得分:0)

试着看看groovy!

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

此外,它还有许多Python教客熟悉的高级结构 从地图,列表,sql,xml中解脱出来的一些扩展,你猜对了 - 文件IO。