如何在 Java 中使用檔案和輸入/輸出
來源:
Medium 本教學介紹如何在 Java 中建立、讀取、寫入和刪除檔案。您還將了解File、InputStream和OutputStream類別的工作原理。
介紹
在 Java 中,檔案由File類別表示。
File類別提供了建立、讀取、寫入和刪除檔案的方法。輸入/輸出 (I/O) 是在程式和外部來源(例如檔案、網路套接字或控制台)之間傳輸資料的過程。Java提供了許多用於輸入/輸出的類,包括
InputStream和
OutputStream類。
建立文件
要建立文件,您可以使用
File.createNewFile()方法。如果同名檔案不存在,它將建立一個新檔案。如果這樣的檔案已經存在,則
createNewFile()方法將會拋出
IOException。以下是如何在目前目錄中 建立名為
myfile.txt的新檔案的範例:
File myFile = new File("myfile.txt");
myFile.createNewFile();
讀取文件
要在 Java 中讀取文件,可以使用
FileInputStream類別。它提供了從文件中讀取位元組的方法。要讀取文件的內容,您應該使用
read()方法。此方法從檔案中讀取一個位元組並傳回該位元組的值。例如,以下程式碼讀取檔案
myfile.txt的內容並將其列印到控制台:
File myFile = new File("myfile.txt");
FileInputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, bytesRead));
}
inputStream.close();
錄音文件
要寫入文件,您可以使用
FileOutputStream類別。它提供了將位元組寫入文件的方法。若要將字串的內容寫入文件,請使用
write()方法。此方法將指定數組中指定數量的位元組寫入檔案。以下是如何寫字串「Hello, world!」的範例。前往
myfile.txt檔案:
File myFile = new File("myfile.txt");
FileOutputStream outputStream = new FileOutputStream(myFile);
byte[] buffer = "Hello, world!".getBytes();
outputStream.write(buffer);
outputStream.close();
刪除文件
要在 Java 中刪除文件,您應該使用
File.delete()方法。如果要刪除的檔案不存在,則
delete()方法將傳回
false。
以下是刪除myfile.txt檔案的程式碼範例:
File myFile = new File("myfile.txt");
myFile.delete();
結論
在這篇文章中,我們討論了使用檔案和 I/O Java 的基礎知識。您學習如何建立、讀取、寫入和刪除檔案。您還了解了
File類別以及
InputStream和
OutputStream類別。
Objects 類別的實用方法 - 如何使用它們
來源:
Inside Java 透過這篇文章,您將加深對Objects類別中提供的各種方法的了解。Java 中的Objects 類別具有許多實用方法,可以輕鬆地對物件執行各種操作。
Objects類別在 JDK 版本中經歷了許多更新:在 JDK 8 和 9 中進行了非常重大的更新,在 JDK 16 和 19 中進行了較小的更新。讓我們看看如何使用
Objects類別。
物體比較
Objects提供了幾個用於比較兩個物件的值的選項。
使用物件實現的主要好處是可以安全地防止
null出現。
等於()
下面是比較兩筆記錄的範例。
record RaceTime(String runnerName, Duration time) {}
RaceTime nullValue = null;
RaceTime billy =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime copyOfbilly =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime nicolai =
new RaceTime("Nicolai Parlog", Duration.of(180, ChronoUnit.SECONDS));
nullValue.equals(billy);
Objects.equals(nullValue, billy);
Objects.equals(billy, nicolai);
Objects.equals(billy, copyOfbilly);
深等於()
在
Objects類別中,您也可以使用deepEquals()來比較兩個陣列。與常規
equals()不同,這將比較儲存在陣列中的值,這應該會導致更一致的結果。從根本上來說,這個方法透過
Arrays.deepEquals()。
record RaceTime(String runnerName, Duration time) {}
RaceTime billy =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime nicolai =
new RaceTime("Nicolai Parlog", Duration.of(180, ChronoUnit.SECONDS));
RaceTime[] raceTimes1 = new RaceTime[] { billy, nicolai };
RaceTime[] raceTimes2 = new RaceTime[] { billy, nicolai };
Objects.equals(raceTimes1, raceTimes2);
Objects.deepEquals(raceTimes1, raceTimes2);
比較()
物件也有一個
compare()方法,它可以接受兩個物件和
一個Comparator<T>。
Compare()方法是
物件中為數不多的null不安全方法之一,因為如果其參數之一為
null ,則它不會有可接受的傳回值。
record RaceTime(String runnerName, Duration time) {}
class RaceTimeComparator implements Comparator<RaceTime> {
@Override
public int compare(RaceTime o1, RaceTime o2) {
return o1.time.compareTo(o2.time);
}
}
RaceTime billy =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime nicolai =
new RaceTime("Nicolai Parlog", Duration.of(180, ChronoUnit.SECONDS));
Objects.compare(billy, nicolai, new RaceTimeComparator());
Objects.compare(null, nicolai, new RaceTimeComparator());
字串和哈希碼
Objects類別提供將物件轉換為String和HashCode值的方法。同樣,這些方法的主要優點是它們不會出現空值。
轉換為字串
其中一個更有趣的方法是
toString(obj, nullDefault),它在發生錯誤時提供預設值。這表示
toIdentityString(obj)傳回所傳遞物件的
toString()和
hashCode(),就好像這些方法都沒有被覆寫一樣。
record RaceTime(String runnerName, Duration time) {}
RaceTime nullValue = null;
RaceTime billy =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime nicolai =
new RaceTime("Nicolai Parlog", Duration.of(180, ChronoUnit.SECONDS));
Objects.toString(billy);
Objects.toString(nullValue);
Objects.toString(nullValue, "Did not finish");
Objects.toIdentityString(billy);
轉換為哈希碼
物件還提供了將物件轉換為其哈希碼值的方法。
record RaceTime(String runnerName, Duration time) {}
RaceTime nullValue = null;
RaceTime billy =
new RaceTime("Billy Korando", Duration.of(90, ChronoUnit.SECONDS));
RaceTime nicolai =
new RaceTime("Nicolai Parlog", Duration.of(180, ChronoUnit.SECONDS));
Objects.hashCode(nullValue);
Objects.hashCode(billy);
Objects.hash(billy, nicolai);
檢查是否為空
Objects類別提供了多種檢查和處理
null 的方法。
在 null 上拋出 NullPointException
如果傳遞的值為
null ,則requireNonNull(obj)方法將會拋出
NullPointException。
record RaceTime(String runnerName, Duration time) {
RaceTime{
runnerName = Objects.requireNonNull(runnerName);
time = Objects.requireNonNull(time);
}
}
在 null 上拋出 NullPointException 並向使用者傳送訊息
如果傳遞的值為null ,則requireNonNull(obj, String)方法將引發
NullPointException錯誤並向使用者傳送訊息。
record RaceTime(String runnerName, Duration time) {
RaceTime{
runnerName = Objects.requireNonNull(runnerName, "runner name required!");
time = Objects.requireNonNull(time, "race time required!");
}
}
傳回 null 的預設值
如果
obj為
null ,則requireNonNullElse(obj, defaultValue)方法將傳回傳遞的
defaultValue。
record RaceTime(String runnerName, Duration time) {
RaceTime{
runnerName = Objects.requireNonNullElse(runnerName, "John Smith");
time = Objects.requireNonNullElse(time, Duration.ZERO);
}
}
使用供應商
Objects類別也提供
requireNonNull(obj,Supplier<String>)和
T requireNonNullElseGet(T,Supplier<T>)方法,可用來提供訊息或預設值。僅當建立訊息或預設值會對效能產生重大影響時才應使用它們。
record RaceTime(String runnerName, Duration time) {
static Supplier<String> noNameMsgSupplier = () -> "runner name required!";
static Supplier<String> noTimeMsgSupplier = () -> "race time required!";
RaceTime{
runnerName = Objects.requireNonNull(runnerName, noNameMsgSupplier);
time = Objects.requireNonNull(time, noTimeMsgSupplier);
}
}
record RaceTime(String runnerName, Duration time) {
static Supplier<String> noNameValueSupplier = () -> "John Smith";
static Supplier<Duration> noTimeValueSupplier = () -> Duration.ZERO;
RaceTime{
runnerName = Objects.requireNonNullElseGet(runnerName, noNameValueSupplier);
time = Objects.requireNonNullElseGet(time, noTimeValueSupplier);
}
}
預測性空值檢查
物件提供了在謂詞中使用的
空檢查,儘管它也可以在其他場景中使用。
record RaceTime(String runnerName, Duration time) {}
RaceTime nullValue = null;
Objects.nonNull(nullValue);
Objects.isNull(nullValue);
索引檢查
最後,
Objects類別提供了幾個選項,用於在遍歷File、
String、
Collection或類似物件時檢查索引位置。其中一些方法最近已新增到 JDK 16 中。
int checkIndex(int index, int length)
int checkFromToIndex(int fromIndex, int toIndex, int length)
int checkFromIndexSize(int fromIndex, int size, int length)
long checkIndex(long index, long length)
long checkFromToIndex(long fromIndex, long toIndex, long length)
long checkFromIndexSize(long fromIndex, long size, long length)
GO TO FULL VERSION