[英]Trying to copy a file using RandomAccessFile in Java
我试图使用Java中的RandomAccessFile复制简单的.txt数据。 我已经编写了以下程序:
我的主要方法:
public static void main(String args[]){
File original = new File("C:\\Users\\Tjatte\\Documents\\testdatei.txt");
File copy = new File("C:\\Users\\Tjatte\\Documents\\testdateicopy.txt");
copy(original,copy);
}
我的静态复制方法
public static void copy(File main,File copy){
try{
RandomAccessFile data = new RandomAccessFile(main,"rw");
RandomAccessFile datacopy = new RandomAccessFile(copy,"rw");
datacopy.seek(0);
for(int i = 0; i < main.length(); i++){
datacopy.write(data.read());
data.skipBytes(i);
}
}catch(IOException e){
}
}
每当我要复制文本为“ hello”的文件时,复制文件中的输出为“halÿÿ” ...但是它必须为“ hello”。
感谢您的帮助! 提前致谢。
我更喜欢Files.copy(Path, OutputStream)
和try-with-resources
像
public static void copy(File main, File copy) {
try (OutputStream fos = new FileOutputStream(copy)) {
Files.copy(main.toPath(), fos);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
或 ,如@Andreas在评论中指出的那样,请使用Files.copy(Path, Path, CopyOption...)
try {
Files.copy(main.toPath(), copy.toPath());
} catch (IOException e) {
e.printStackTrace();
}
不要跳过字节。 似乎是“读取”操作会自动将指针移动到下一个字符。
因此,只需删除带有“ data.skipBytes(i);”的行。
您也可以这样:
public class CopyFileContent{
static final String FILEPATH = "C:../../inputfile.txt";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 150, 23)));
writeToFile(FILEPATH, "Hello", 22);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.