簡體   English   中英

使用Files API讀寫.txt文件,和使用BufferredWriter不一樣?

[英]Using Files API to read and write to .txt file, not the same as using BufferredWriter?

我正在 Hyperskill 上做文本編輯器項目,除了第二階段測試 #18 之外一切都很好。 我付了錢來查看解決方案,但我不明白我的代碼和成功的代碼之間有什么區別。 我希望有人能解釋為什么它有效而我的無效?

我得到的錯誤是; “保存和加載相同文件后文本應該相同”

據我所知,它是一樣的。 我 select 所有帶有 CTRL-A 的文本(在JTextArea中)並選擇換行符和空格。

我看不出我的代碼和一些通過測試的正確解決方案之間有什么區別。 我的代碼執行所需的操作,輸入 / output 以字節為單位,應該收集任何空白字符或換行符,對吧?

誰能告訴我(保存到文件方法)我不成功的代碼之間的最終區別是什么 -

try {
        Files.write(Path.of("./"
                            + textField.getText()),                     
                            textArea.getText().getBytes());
} catch (IOException ioException) {
        ioException.printStackTrace();
}

這是以字節為單位寫入文件,不是嗎? 與成功的代碼相比——

String content = textArea.getText();
try (final BufferedWriter writer = 
             Files.newBufferedWriter(Path.of("./"
                            + textField.getText()));) {
        writer.write(content);
        writer.flush();
} catch (IOException ioException) {
        System.out.println("Cant save file" + ioException);
}

為了讀取文件,我不成功的代碼是 -

try {
         String content = new String(Files.readAllBytes(Path.of("./"
                                            + textField.getText())));
         textArea.setText(content);
} catch (IOException ioException) {
         ioException.printStackTrace();
}

成功的代碼是 -

try {
         textArea.setText(new String(Files.readAllBytes(Paths.get(path))));
} catch (IOException e) {
         System.out.println("Cant read file!!!");
         return null;
}

有什么區別? 我以稍微不同的方式使用文件,但我只能看到它正在將字節轉換為字符串,反之亦然。

如果我們假設您的路徑名是正確的,那么兩種不同的寫入方法可能使用不同的編解碼器。

String#getBytes使用平台默認字符集。

Files.newBufferedWriter使用 UTF8。

因此,如果您的平台默認值不是 utf8,那么您可能會寫入不同的字節。 也許試試。

string.getBytes(StandardCharsets.UTF_8);

暫無
暫無

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

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