JavaRush /Java 博客 /Random-ZH /喝咖啡休息#229。如何在 Java 中使用文件和输入/输出。Objects 类的实用方法

喝咖啡休息#229。如何在 Java 中使用文件和输入/输出。Objects 类的实用方法

已在 Random-ZH 群组中发布

如何在 Java 中使用文件和输入/输出

来源: Medium 本教程介绍如何在 Java 中创建、读取、写入和删除文件。您还将了解FileInputStreamOutputStream类的工作原理。 喝咖啡休息#229。 如何在 Java 中使用文件和输入/输出。 Objects 类的实用方法 - 1

介绍

在 Java 中,文件由File类表示。File类提供了创建、读取、写入和删除文件的方法。输入/输出 (I/O) 是在程序和外部源(例如文件、网络套接字或控制台)之间传输数据的过程。Java提供了许多用于输入/输出的类,包括InputStreamOutputStream类。

创建文件

要创建文件,您可以使用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类以及InputStreamOutputStream类。

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);//NPE
Objects.equals(nullValue, billy);// false
Objects.equals(billy, nicolai);// false
Objects.equals(billy, copyOfbilly);// true

深等于()

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);// false
Objects.deepEquals(raceTimes1, raceTimes2);// true

比较()

对象还有一个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());//-1
Objects.compare(null, nicolai, new RaceTimeComparator());//NPE

字符串和哈希码

Objects类提供将对象转换为StringHashCode值的方法。同样,这些方法的主要优点是它们不会出现空值

转换为字符串

更有趣的方法之一是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);//RaceTime[runnerName=Billy Korando, time=PT1M30S]
Objects.toString(nullValue);//null
Objects.toString(nullValue, "Did not finish");//Did not finish
Objects.toIdentityString(billy);//ObjectsExamples$1RaceTime@251a69d7

转换为哈希码

对象还提供了将对象转换为其哈希码值的方法。
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);//0
Objects.hashCode(billy);//[HashValue]
Objects.hash(billy, nicolai);//[HashValue]

检查是否为空

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 的默认值

如果objnull ,则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);//false
Objects.isNull(nullValue);//true

索引检查

最后,Objects类提供了几个选项,用于在遍历FileStringCollection或类似对象时检查索引位置。其中一些方法最近已添加到 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)
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION