使用RandomAccessFile(Java)读取txt文件

时间:2016-01-13 21:02:01

标签: java file io randomaccessfile

我尝试输出文本文件的内容。但我不知道如何使用RandomAccessFile。我没有在谷歌找到好的例子。我希望得到一些帮助。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadTextFile {

    public static void main(String[] args) throws IOException {

        File src = new File ("C:/Users/hansbaum/Documents/Ascii.txt");
        cat(src);
    }

    public static void cat(File quelle){
        try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){

//          while(datei.length() != -1){        
//              datei.seek(0); //
//          }               
        } catch (FileNotFoundException fnfe) {
            System.out.println("Datei nicht gefunden!");
        } catch (IOException ioe) {
            System.err.println(ioe);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

doc

相关
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
        String line;
        while ( (line = datei.readLine()) != null ) {
            System.out.println(line);
        }

        System.out.println();
    } catch (FileNotFoundException fnfe) {
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

答案 1 :(得分:0)

是什么让你认为你需要一个RandomAccessFile?最简单的方法可能是使用nio的便捷方法。有了这些,读取文件就像在Java中一样接近单行。

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
class Test {
  public static void main(String[] args) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get("./Test.java"), StandardCharsets.UTF_8);
    for (String l: lines)
      System.out.println(l);
  }
}

请注意,如果您碰巧使用非常大的文件,这不是一个好主意,因为它们可能不适合内存。

答案 2 :(得分:0)

尝试从StreamFileChannelread在另一个文件write中创建out.txt,如下所示:

        try (RandomAccessFile datei = new RandomAccessFile(quelle, "r").getChannel();){

        // Construct a stream that reads bytes from the given channel.
        InputStream is = Channels.newInputStream(rChannel);

        File outFile = new File("out.txt");

        // Create a writable file channel
        WritableByteChannel wChannel = new RandomAccessFile(outFile,"w").getChannel();

        // Construct a stream that writes bytes to the given channel.
        OutputStream os = Channels.newOutputStream(wChannel);

        // close the channels
        is.close();
        os.close();