2016-01-13 116 views
-1

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

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

你点击搜索按钮,当你使用谷歌? –

+0

https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html 应该会帮助你 – amkz

回答

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

非常感谢。我们的学校讲座仅包括阅读方法。 –

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

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

+0

它只是为了学校。 –

0

尝试在另一个文件out.txt像这样来创建FileChannelStreamreadwrite

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