/**
* Use RandomAccessFile to reverse a file.
*
* To use this program, specify the name of the file.
* For example, to reverse a file called test.txt use the
* following command line:
*
* java ReverseFile test.txt
*
*/
package FileIO;
import java.io.*;
/**
* @author Administrator
*
*/
public class ReverseFile {
/**
* @param args
*/
public static void main(String[] args) {
// First make sure the a file has been specified.
if (1 != args.length) {
System.out.println("Usage: ReverseFile name");
return ;
}
RandomAccessFile raf;
try {
// Open the file.
raf = new RandomAccessFile(args[0], "rw");
} catch (FileNotFoundException exc) {
System.out.println("Cannot Open File");
return ;
}
try {
int x;
int y;
// Reverse the file.
for (long i = 0, j = raf.length() - 1; i < j; ++i, --j) {
// Read the next set of bytes
raf.seek(i);
x = raf.read();
raf.seek(j);
y = raf.read();
// Swap the bytes
raf.seek(j);
raf.write(x);
raf.seek(i);
raf.write(y);
}
} catch (IOException exc) {
System.out.println("Error Writing File");
}
try {
raf.close();
} catch (IOException exc) {
System.out.println("Error Closing File");
}
}
}
ReverseFile
最新推荐文章于 2023-04-17 19:28:40 发布