类似python的Java IO库?

类似python的Java IO库?,java,python,file-io,Java,Python,File Io,Java不是我的主要编程语言,所以我可能会问一个显而易见的问题 但是在Java中是否有一个简单的文件处理库,如在中 例如,我只想说: File f = Open('file.txt', 'w') for(String line:f){ //do something with the line from file } 谢谢 更新:stackoverflow自动接受了一个奇怪的答案。这和我的悬赏有关——所以如果你想看到其他答案,只需向下滚动 在Java中逐行读取文件: Buffered

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

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

例如,我只想说:

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


更新:stackoverflow自动接受了一个奇怪的答案。这和我的悬赏有关——所以如果你想看到其他答案,只需向下滚动

在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文档。请查看以获取更详细的信息

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

BufferedReader in = new BufferedReader(
    new InputStreamReader(new FileInputStream("myfile.txt"), "UTF-8"));

如果您已经依赖于,并且这可能是一个替代方案:

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

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

我想的是:

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       
    }
}

您可以使用它在Java中运行Python语法。

这里有一个很好的例子:

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

API非常有用:
你也可以用正则表达式解析文件。

我从不厌倦为谷歌拉皮条,这会让你从。。。嗯,Java中的大多数东西

那么:

for (String line : Files.readLines(new File("file.txt"), Charsets.UTF_8)) {
   // Do something
}
如果您有一个大文件,并且希望逐行回调(而不是将整个内容读入内存),您可以使用,它添加了一些样板文件(由于缺少闭包…叹气),但仍然阻止您处理读取本身以及所有相关的
异常

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;
  }
});
然后您的代码可能是:

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'!");
  }
});

它相应地更干净。

使用guava io的
文件.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;
                }
            });
    }
}
导入java.io.File;
导入java.io.IOException;
导入com.google.common.base.charset;
导入com.google.common.io.Files;
导入com.google.common.io.LineProcessor;
公共类GuavaIoDemo{
公共静态void main(字符串[]args)引发异常{
int result=Files.readLines(新文件(“/home/pascal/.vimrc”)//
Charsets.UTF_8,//
新的LineProcessor(){
整数计数器;
公共整数getResult(){
返回计数器;
}
公共布尔processLine(字符串行)引发IOException{
计数器++;
系统输出打印项次(行);
返回true;
}
});
}
}
一些警告:

  • 使用默认系统编码,但您应该
  • 扫描仪接受I/O异常,因此您可能希望在最后检查是否正确处理错误
试试看groovy

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

此外,它还有许多蟒蛇学家熟悉的更高层次的构造,还有

有许多扩展可以减轻映射、列表、sql、xml和您猜到的文件IO的痛苦。

Hm。。看起来仍然很笨重:-(是的,但这就是Java的标准API的工作方式,Java不是最简洁的语言……所以,除了逐行读取文件的玩具示例之外,你还想做什么呢?这并不是那么笨重的IMHO。好吧,基本上和python的文件对象一样。它也有二进制模式。我从来没有遇到过问题。它应该是cool在eclipse中为其提供一个代码模板,该模板将整个文件读入一个
字符串
,然后将整个文件拆分到内存中…如果文件很大,可能会占用大量内存。我支持@Jesper的考虑。内存中的字符串太多,可能会导致应用程序死机(OutOfMemoryError)在添加赏金之前,我刚刚添加了一个替代方案,我还推荐Jespers answer。对于较小的文件,它可以正常工作。FileUtils有一个方法readLines,它返回字符串列表。我尝试远离Apache commons中的任何内容,因为这通常意味着在Apache commons中包含所有100亿个其他依赖项。这很有趣ting,你可以让它看起来像Python。我会调用类
File
其他东西,以避免与Java自己的
Java.io.File
混淆。使
删除()
文件迭代器中的方法
抛出
UnsupportedOperationException
,而不是将其保留为空。谢谢!我不确定如何在那里删除;-)不过,我想我会保留文件名,因为对于名称空间,我看不出有任何问题。我对此做了更多的更改-我真的希望有java背景的人来看看。明天我将在pastebin上发布我的版本。Drozzy,我认为不管代码的长度如何,实际上最好将代码留在这里。我总是认为当我回答地球上所有其他网站都将消失时(是的,甚至是MSDN、维基百科等)。这里的答案应该能够站在自己的立场上。我没有问题链接到其他网站以获取更多细节,但“肉”应该在这里。让我们想想如果pastebin破产,这个答案会发生什么(或者更糟糕的是,你开始将他们的投资货币化)。这个答案变得毫无用处,因为它基本上是对问题的引用。我甚至会+2你(Q&a)试图说服你把代码留在这里:-)+1是为了聪明,但是你的迭代器需要确保如果在next()中发生IOException,文件将被关闭我记得你详细的回答为什么要删除它?我没有,我只是把我的代码移到了pastebin,因为它变得很长。如果你觉得有冒险精神,请查看scala。它允许你完成这些类型的任务。Th
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'!");
  }
});
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;
                }
            });
    }
}
  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();
    }
  }