简体   繁体   中英

Read a txt File with RandomAccessFile (Java)

I try to output the content of a text file. But I don't know how to work with the RandomAccessFile. I haven't found good examples at google. I hope for some help.

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

related from 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);
    }

What makes you think you need a RandomAccessFile? The easiest way is probably to use nio's convenience methods. With those, reading a file is as close to a one-liner as it gets in 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);
  }
}

Be aware however that this is not a good idea if you happen to work with very large files as they might not fit into memory.

Try to create Stream from FileChannel to read and write in another file out.txt like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM