1

这段代码的等价物是什么Java?我已经放了一部分,我对 I/O 部分感兴趣:

int fd = open(FILE_NAME, O_WRONLY);  
int ret = 0;  
if (fd == -1) {         
    exit(EXIT_FAILURE);  
}  
while (1) {  
    ret = write(fd, "\0", 1);  
}  

更新:
代码不会复制文件。它只会每 X 秒在文件中写入一个字节(?)/char(?)(不确定是什么)

4

3 回答 3

3

这基本上就是你想要的。

try {
  FileOutputStream os = new FileOutputStream(FILENAME);
  while( true ){
     os.write(0);
     Thread.sleep(2000);  // wait 2 seconds before the next write
  }
}
catch( FileNotFoundException e ){
  System.err.println("watchdog error: " + e.getMessage())
  System.exit(1);
}

如果您真的想像 C 代码一样忽略所有“写入”错误,请将 os.write 更改为:

try {
  os.write(0);
}
catch( Exception we ){
  //ignoring write exception 
}
于 2013-02-18T14:38:29.410 回答
1
public static void main(String[] args) throws IOException, InterruptedException {
    //open the file (throws exception if failed)
    FileOutputStream fstream = new FileOutputStream("fName"); 

    while (true) {
         //write "\0" in the file (throws exception if failed)
         fstream.write(0); 
         //sleep for 1000ms, throw exception if interrupted
         Thread.sleep(1000);
     }
 }
于 2013-02-18T14:39:47.933 回答
0
Filereader file = new Filereader("filename");
BufferedReader reader = new BufferedReader();
String line = "";

FileWriter fstream = new FileWriter("fName");
BufferedWriter fbw = new BufferedWriter(fstream);

while ((line = reader.readLine()) != null) {

    fbw.write(line + "\n");

}

你的意思是这样的?从一个文件读取并写入另一个文件。

于 2013-02-18T14:30:38.527 回答