[英]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.