簡體   English   中英

有沒有辦法在文件之間添加一些文本而不使用 FileChannel 覆蓋文件的任何現有內容

[英]Is there a way to add some text in between a file without overwriting any existing content of the file using FileChannel

假設我有一個 txt 文件:Hello World 我只想在中間添加“My”,這樣文件看起來像這樣:Hello My World 我試圖使用 java.nio.channels.FileChannel 類來實現這一點,正如你可以尋求的文件指針。但是當我將文件指針移動到文件的中間並寫入文本時,它會替換前面的文本,而不是將其向前推。

我的代碼:

try{
         FileChannel out=FileChannel.open(Paths.get("E:\\trial.txt"),StandardOpenOption.WRITE);
         out.position(6);
         out.write(ByteBuffer.wrap("My ".getBytes()));
        }catch(IOException e){
            e.printStackTrace();
        }

輸出:Hello My ld

期望輸出:你好我的世界

如您所見,“My”替換了“Wor”,我不希望替換任何文本,它應該只在文件之間添加“My”。 我知道我可以通過讀取“世界”(指定位置后的剩余文本)並創建“我的世界”的 ByteBuffer 然后將其寫入所需位置來實現。

這可以完成以下工作:

try{
         FileChannel out=FileChannel.open(Paths.get("E:\\trial.txt"),StandardOpenOption.READ,StandardOpenOption.WRITE);
         out.position(6);
         ByteBuffer b=ByteBuffer.allocate(20);
         b.put("My ".getBytes());
         out.read(b);
         out.position(6);
         b.flip();
         out.write(b);
        }catch(IOException e){
            e.printStackTrace();
        }

但是,是否有一種更簡單/直接的方法來執行此操作,您只需將文件指針設置為特定位置並寫入只添加文本而不替換現有文本?

您可以瀏覽文件中的所有行並將它們保存在一個數組中。 然后你只是循環,最后在里面打印你的東西。

你可以用這兩種方法

這是用於閱讀文件

public static List<String> readFile(String filePath) {
    List<String> list= new ArrayList<>();
    try {
        File myObj = new File(filePath);
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            list.add(data);
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

    return list;
}

這用於寫入文件

public static void write(String filePath, String line) {
    try {
        final Path path = Paths.get(filePath);
        Files.write(path, Arrays.asList(line), StandardCharsets.UTF_8,
                Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
    } catch (final IOException ioe) {
        // Add your own exception handling...
    }
}

第一個方法返回一個字符串列表。 每一行都是列表的一個元素。 因此,您可以訪問包含要修改的句子的列表元素,然后您可以使用循環在文件中寫入每一行。

public static void main (String[] args){
    List<String> lines = readFile(filePath);

    lines.get(0) = "Hello My world";

    for (String line : lines
         ) {
        write(line, filePath);
    }
}

祝你今天過得愉快!!!

對於順序文本閱讀,應該使用 Reader 將使用編碼 Charset 來讀取二進制數據。

解決方案是將該閱讀器包裝在您自己的擴展FilterReader的類中。

所需的代碼是大量的,覆蓋了兩種讀取方法。 可能更好地搜索一些替換實現(可能是 Sed.java)。

好的 所以似乎沒有直接的方法存在。我知道答案中建議的大多數方法。我只是想知道是否有直接方法,因為這似乎是一個非常簡單和基本的問題。感謝您的回答.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM