4 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
以下是一些可能的解決方案:
將方法簽名更改為
public void writeToFile()
. 不要退回Path
. (但這可能對你不起作用:你可能需要.Path
)return null;
在方法末尾添加。這樣做的缺點(diǎn)是調(diào)用者需要處理null
返回的情況......否則當(dāng)他們嘗試使用不存在的 時(shí)它將獲得 NPEPath
。這相當(dāng)于您的“丑陋”解決方案。從風(fēng)格的角度來看,哪個(gè)更好是值得商榷的。(一個(gè)教條的“結(jié)構(gòu)化編程”人會(huì)說你的方式更好?。?/p>
更改簽名以返回為
Optional<Path>
. 這是比返回顯式更好的選擇null
。如果你正確地實(shí)現(xiàn)它,調(diào)用者實(shí)際上被迫處理“缺席”的情況。刪除try catch并將方法的簽名更改為
public Path writeToFile() throws IOException
. 調(diào)用者必須處理已檢查的異常,但這可能是件好事!
我應(yīng)該指出您的代碼沒有正確處理資源。您應(yīng)該對資源使用 try以確保由創(chuàng)建的流FileWriter
始終關(guān)閉。否則存在泄漏文件描述符的風(fēng)險(xiǎn),最終可能導(dǎo)致意外的 I/O 錯(cuò)誤。

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您不想返回,null我會(huì)更喜歡使用Optionaljava 8
public Optional<Path> writeToFile() {
try {
Path tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFilePath.toFile()));
for (List<Integer> arr : arrays) {
// Convert array ints to strings, join it to single string and write
bw.write(arr.stream()
.map(String::valueOf)
.collect(Collectors.joining(" ")));
bw.newLine();
}
bw.close();
return Optional.of(tempFilePath);
} catch (IOException e) {
e.printStackTrace();
}
return Optional.empty()
}
所以在調(diào)用者方法中你可以使用
public void ifPresent(消費(fèi)者消費(fèi)者)
或者
公共布爾 isPresent()

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
另一種解決方案不是吃IOException(反模式),而是將其轉(zhuǎn)換為適當(dāng)?shù)淖宇怰untimeException并從 catch 塊中拋出。
此外,在您的示例中,您正在泄漏文件處理程序,而不是關(guān)閉FileWriter異常。
public Path writeToFile() {
final Path tempFilePath;
try {
tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");
} catch (IOException e ) {
throw new MyRuntimeException(
"Cannot create sorting_test temp file",
e
);
}
try (final FileWriter fw = new FileWriter(tempFilePath.toFile())) {
try(final BufferedWriter bw = new BufferedWriter(fw)) {
for (List<Integer> arr : arrays) {
// Convert array ints to strings, join it to single string and write
bw.write(arr.stream()
.map(String::valueOf)
.collect(Collectors.joining(" ")));
bw.newLine();
}
}
return tempFilePath;
} catch (IOException e) {
throw new MyRuntimeException(
"Cannot write to " + tempFilePath,
e
);
}
}
添加回答
舉報(bào)