RUVIDEO
Поделитесь видео 🙏

File input/output Basic tutorial in Java - Get an input from a file using java.io.FileReader

📁 Обучение 👁️ 16 📅 03.12.2023

File input/output Tutorial in Java - Get an input from a file using java.io.FileReader

In this video, I will show you how to input data in a Java program using a file stored on our computer.
I will do another video in which, I will discuss how to save the output of a Java program on a file
On this channel, I have already talked about how you can get input from the keyboard and also how you can send output to the screen or dialog box. But both methods of inputting data in a program using a keyboard and even outputting results on the screen have limitations.
Let’s say for example that you have a large amount of data to input in your program, if you have to type it at the keyboard you will probably waste a lot of time, you will sometimes make mistakes while typing and this can lead to unexpected results.
So, the solution, to these problems I just mentioned, is to use files as the source of input

Now, let’s talk about the syntax
As you can see on the screen, I have used the Scanner object and have initialized it to an input source other than the standard input device
Scanner input_file = new Scanner(new FileReader(“MyFile.doc”));

Scanner here is the predefined class used to create an input object and it is contained in the java.util package
input_file is the name I have chosen to give to the input object I am creating
new is a keyword
FileReader is the special class in Java that allows us to get input from a file
The class FileReader is contained in the package java.io

Finally, MyFile.txt is referring to the file that will be used as the input source
And, here you have to make sure to type in the path to where your file is saved on your computer
Also, we have two backward slashes because the backward slash is an escape character that is why we need to have two backward slashes here for the program to read it as one backward slash
If I remove one backward slash, I will get an error; so I need to keep the two slashes

Also note that, if we wanted to get input from the keyboard, we would simply write System.in in between the brackets
Since, in this case, we rather want to use a file as the source of input, let’s then use the FileReader class

Now, in order to use the object input_file to input data from the file MyFile.doc, we have to use predefined methods like next, nextInt, nextDouble and so on

Here is my file and I have written this information that is corresponding to the first name, name, age, and height of a person

So, in order to verify that my file is being used as the source of input I will store the result of these methods in appropriate variables
And then, I will do a System.out.println() to show you that my program is getting its input from the file MyFile.txt

String firstname = input_file.next();
String name = input_file.next();
int age = input_file.nextInt();
double height = input_file.nextDouble();

System.out.println(firstname);
System.out.println(name);
System.out.println(age);
System.out.println(height);

#codingriver
#java
#programming

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «File input/output Basic tutorial in Java - Get an input from a file using java.io.FileReader», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.