[英]Trying to copy a file using RandomAccessFile in Java
i am trying to copy a simple .txt data using RandomAccessFile in Java. 我试图使用Java中的RandomAccessFile复制简单的.txt数据。 I´ve coded the following program:
我已经编写了以下程序:
My Main Method: 我的主要方法:
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);
}
My static copy method 我的静态复制方法
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){
}
}
Whenever i want to copy a file with the text "hello" in it, the output in the copied file is "halÿÿ"... But it has to be "hello". 每当我要复制文本为“ hello”的文件时,复制文件中的输出为“halÿÿ” ...但是它必须为“ hello”。
I appreciate any help! 感谢您的帮助! Thanks in advance.
提前致谢。
I would prefer Files.copy(Path, OutputStream)
and a try-with-resources
close like 我更喜欢
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();
}
}
or , as pointed out by @Andreas in the comments, use Files.copy(Path, Path, CopyOption...)
like 或 ,如@Andreas在评论中指出的那样,请使用
Files.copy(Path, Path, CopyOption...)
try {
Files.copy(main.toPath(), copy.toPath());
} catch (IOException e) {
e.printStackTrace();
}
Don't skip bytes. 不要跳过字节。 Seems like "read" operation will move the pointer to the next character automatically.
似乎是“读取”操作会自动将指针移动到下一个字符。
So, just delete the line with "data.skipBytes(i);" 因此,只需删除带有“ data.skipBytes(i);”的行。
You can this way too: 您也可以这样:
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.