簡體   English   中英

使用 FileWriter 在 Java 中寫入文件

[英]Writing to a File in Java using FileWriter

我想在一組字符后寫入文件。 例如,如果我想將xyz寫入包含字符串hello world的文件test.txt 我想寫在字母w 輸出應該是文件中的hello wxyzorld

它是如何做到的? 使用FileWriterBufferedWriter我可以寫入文件,但不能寫入某個位置。 如果有任何我可以做到的,你能幫我嗎?

public static void main(String[] args) {
    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("/path/to/test.txt")));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        int offset = 7;

        while((line = bufferedReader.readLine()) != null) {
                for(int i=0; i<line.length(); i++) {
                    if(i == offset) {
                        stringBuilder.append("xyz" + line.charAt(i));
                    } else if(i == line.length()-1) {
                        stringBuilder.append(line.charAt(i) +"\n");
                    } else {
                        stringBuilder.append(line.charAt(i));
                    }
                }
        }

        System.out.println(stringBuilder);
        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

也許是這樣的? 您可以將其余的行相應地附加到您的 StringBuilder。

暫無
暫無

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

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