2012-09-12 105 views

回答

2

我不是一个Java程序员,但我在网上搜索了一下,看起来Java有一个RandomAccessFile,你可以用"rw"模式打开它。

+2

无需检查;只是setLength(0); –

+0

为此欢呼。我在写作时不得不跑掉,并忘记检查我是否回答了整个问题=/ – paddy

+0

感谢男人,很好的回答:) – AndroidLearner

0

看起来像你想FileOutputStreamFileWriter,这取决于你想写什么样的数据。它们中的任何一个都可以用文件名来实例化。

FileOutputStream fis = new FileOutputStream("/path/to/file"); 
FileWriter fw = new FileWriter("/path/to/file2"); 

如果文件已经存在,两者都将会破坏文件。 (尽管构造函数存在用于追加而不是覆盖)

+1

他想要一个可读写的文件。 –

+0

更不用说,这不会被截断,仅仅是破坏。 – oldrinb

1

真正的等价物是使用Files.newByteChannel

final SeekableByteChannel channel = Files.newByteChannel(Paths.get("path"), 
    StandardOpenOptions.READ, StandardOpenOptions.WRITE, 
    StandardOpenOptions.TRUNCATE_EXISTING); 

READWRITE选项确定文件是否应打开供读取和/或写入。

...

TRUNCATE_EXISTING - 如果此选项存在,那么现有的文件被截断为一个大小为0字节。仅当打开文件才能阅读时,此选项将被忽略。

3

看来1.7的java是必需的NIO,所以我的看法是

RandomAccessFile f = new RandomAccessFile(name, "rw"); 
f.setLength(0); 
+0

谢谢你,对不起,不能让你的答案最好,但你的回答也是正确的,谢谢你的帮助。 :) – AndroidLearner

0

达到你想要的东西快速路:

import java.io.*; 
// Create a new file output connected to "myfile.txt" 
out = new FileOutputStream("myfile.txt"); 
// Create a new file input connected to "myfile.txt" 
in = new FileInputStream("myfile.txt"); 

你可能想看看java.io包at the official docs,尤其是RandomAccessFile Classalso this quick guide

相关问题