类似 python 的 Java IO 库?

2022-09-02 11:51:49

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

但是Java中有一个简单的文件处理库,就像python一样

例如,我只想说:

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

谢谢!

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


答案 1

我在想更多的东西:

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

在 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 类都在包 中。请参阅该包的 API 文档。查看 Sun 的 Java I/O 教程,了解更多详细信息。java.io

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

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