JavaRush /Java Blog /Random EN /Coffee break #229. How to work with files and Input/Outpu...

Coffee break #229. How to work with files and Input/Output in Java. Utility methods of the Objects class

Published in the Random EN group

How to work with files and Input/Output in Java

Source: Medium This tutorial explains how to create, read, write and delete files in Java. You'll also learn how the File , InputStream , and OutputStream classes work . Coffee break #229.  How to work with files and Input/Output in Java.  Utility methods of the Objects class - 1

Introduction

In Java, files are represented by the File class . The File class provides methods for creating, reading, writing, and deleting files. Input/output (I/O) is the process of transferring data between a program and an external source, such as a file, network socket, or console. Java provides many classes for input/output, including the InputStream and OutputStream classes .

Creating files

To create a file, you can use the File.createNewFile() method . It will create a new file if a file with the same name does not already exist. If such a file already exists, the createNewFile() method will throw an IOException . Here's an example of how to create a new file called myfile.txt in the current directory:
File myFile = new File("myfile.txt");
myFile.createNewFile();

Reading files

To read a file in Java, you can use the FileInputStream class . It provides methods for reading bytes from a file. To read the contents of a file, you should use the read() method . This method reads one byte from a file and returns the value of the byte. For example, the following code reads the contents of the file myfile.txt and prints it to the console:
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();

Recording files

To write to a file, you can use the FileOutputStream class . It provides methods for writing bytes to a file. To write the contents of a string to a file, use the write() method . This method writes the specified number of bytes from a specified array to a file. Here is an example of how the string “Hello, world!” is written. to the myfile.txt file :
File myFile = new File("myfile.txt");
FileOutputStream outputStream = new FileOutputStream(myFile);
byte[] buffer = "Hello, world!".getBytes();
outputStream.write(buffer);
outputStream.close();

Deleting files

To delete a file in Java, you should use the File.delete() method . If the file you want to delete does not exist, then the delete() method will return false . Here is an example of code that deletes the myfile.txt file :
File myFile = new File("myfile.txt");
myFile.delete();

Conclusion

In this post, we discussed the basics of working with files and I/O Java. You learned how to create, read, write, and delete files. You also learned about the File class and the InputStream and OutputStream classes .

Utility methods of the Objects class - how to work with them

Source: Inside Java With this post, you will improve your knowledge of the various methods provided in the Objects class . The Objects class in Java has many utility methods that make it easy to perform a variety of operations on objects. The Objects class has undergone several updates in JDK releases : there have been very significant updates in JDK 8 and 9, and minor updates in JDK 16 and 19. Let's look at how you can use the Objects class .

Comparison of objects

Objects provides several options for comparing the values ​​of two objects. The key benefit of using the Objects implementation is the safety against null occurrences .

equals()

Below is an example of comparing two records.
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

deepEquals()

In the Objects class, you can also use deepEquals() to compare two arrays . Unlike regular equals() , this will compare values ​​stored in arrays, which should lead to more consistent results. Fundamentally this method goes through 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()

Objects also has a compare() method , which can take two objects and a Comparator<T> . The compare() method is one of the few null -unsafe methods in Objects because it has no acceptable return if one of its arguments is 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

String and HashCode

The Objects class provides methods for converting an object to String and HashCode values . Again, the main advantage of these methods is that they are safe from null occurrences .

Convert to String

One of the more interesting methods is toString(obj, nullDefault) , which provides a default value if an error occurs. This means that toIdentityString(obj) returns the toString() and hashCode() of the passed objects as if neither of these methods had been overwritten.
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

Convert to HashCode

Objects also provides methods to convert an object to its hash code value.
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]

Checking for null

The Objects class provides several methods for checking for and handling null .

Throwing NullPointException on null

The requireNonNull(obj) method will throw a NullPointException if the value passed is null .
record RaceTime(String runnerName, Duration time) {
	RaceTime{
		runnerName = Objects.requireNonNull(runnerName);
		time = Objects.requireNonNull(time);
	}
}

Throwing NullPointException on null with a message to the user

The requireNonNull(obj, String) method will throw a NullPointException error with a message to the user if the value passed is null .
record RaceTime(String runnerName, Duration time) {
	RaceTime{
		runnerName = Objects.requireNonNull(runnerName, "runner name required!");
		time = Objects.requireNonNull(time, "race time required!");
	}
}

Return default value for null

The requireNonNullElse(obj, defaultValue) method will return the passed defaultValue if obj is null .
record RaceTime(String runnerName, Duration time) {
	RaceTime{
		runnerName = Objects.requireNonNullElse(runnerName, "John Smith");
		time = Objects.requireNonNullElse(time, Duration.ZERO);
	}
}

Using Suppliers

The Objects class also provides the requireNonNull(obj, Supplier<String>) and T requireNonNullElseGet(T, Supplier<T>) methods , which can be used to provide a message or a default value. They should only be used if creating a message or default value would have a significant performance impact.
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);
	}
}

Predictive null check

Objects provides null checking for use in predicates, although it can be used in other scenarios as well.
record RaceTime(String runnerName, Duration time) {}

RaceTime nullValue = null;
Objects.nonNull(nullValue);//false
Objects.isNull(nullValue);//true

Index check

Finally, the Objects class provides several options for checking the index position when traversing a File , String , Collection , or similar object. Some of these methods were recently added to 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)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION