Last Updated: April 14, 2021
·
464
· Yuri Filatov

How to work with files? Lifehacks for beginners

What does it mean "file" or "usage of files"?

Working with files means reading from a file and outputting into a file, not working with the console.

Can you work with the console and files at the same time?

Of course, you can.

Usually, the files are in txt format, so make two files "input" and "output" (or every name you like), better in the folder of project, otherwise you need to write then the direction of file.

And here are the lifehacks how to deal with them:

*1. There can be a mistake while trying to read your file. Make sure you've written file "location" correctly.

*2. Moreover, if you are sure, there will be no mistakes, USE
try&catch, otherwise your program is not correct.

Here is the example:

try (...) { ... }

catch (IOException e)

{ e.printStackTrace();

}

*3. Better to work with BufferedReader.

String inputFileName = "input.txt";

try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) { ...

And so with a writer: work with FileWriter

try(FileWriter writer = new FileWriter("output.txt", false)

{

...

catch(IOException ex)

{ System.out.println(ex.getMessage());

}

*4. If you are writing into a file during "for" or "while", remember to start your try before.

*5. So if you work with line reading, you have more opportunities than with symbol reading. There are more and better functions for string.

*6. You can use this "try" for writing once. Why? Because you close "try" and then start a new one, so... you start writing into your file like for the first time.

*7. How do we read with lines?

while ((line = reader.readLine()) != null) {...}

While your line (a simple string) is not empty. It takes a line from a file every time until it is empty, so you work with lines.

*8. How do we write?

writer.write(line);

writer.flush();

Remember, that numeric symbols should be converted into string before writing

That is a small help for all beginners, that want to get accouanted with files, everything else is the same. If you need some help, you can write me anytime.

Good luck in your job!