Working with files in Java - ProgrammerTech
Language:

Search

Working with files in Java

  • Share this:
Working with files in Java

The concept of text files File

Text files ( Files ) Text data is one of the tools used to store data permanently, such as Notepad. Or txt files, any text document called a text file, and we work to save it to stay on the computer for a long time.

Today we will learn how to create text files from within the Java program and how to write inside this text file.

A text file is one of the means used to store permanent text data. We will learn how to create a text file. And write a simple sentence inside it. And how to read from the text file and how to add more data and deal with text files professionally. To deal with text files we must use the io package as follows

import java.io.FileWriter

What is meant in io is the term input output, this library we use to create text files, write inside them, read data and deal with text files.

 

Writing on the text file

The text files are written in Java by using FileOutputStream where the text file is created. In the event that it does not exist and then write on it or write on it directly if it exists.

package ioo;
import java.io.FileWriter;
class Ioo {
     public static void main(String[] args) {
          try{
       FileWriter fw=new FileWriter("E: programmertech.txt");
       fw.write("Data and kaissar and saja");
       fw.close();
          }catch(Exception e) {System.out.println(e.getMessage());}
     }
}

At first, we invoked the io package via the command "import java.io.FileWriter", then entered the main program and specified the file path via the FileWriter class. And the save path was in disk D, then we wrote inside the file via the write function via the fw object, then we closed the file via fw.close and put the code between the try and catch exception. And in the event of an error, we will print the exception that occurred.

 

Reading from the text file

Read from the text file We will use a package other than the previous one to enable us to read from the text file. (We only use this package when we want to read from a text file) and write as .

import java.io.FileReader

Example

package ioo;
import java.io.FileReader;
public class Ioo {
    public static void main(String[] args) {
        try{
            FileReader fr=new FileReader("E: programmertech.txt");
            int i;
            while((i=fr.read())!=-1)
                System.out.print((char)i);
        }catch(Exception e) {}
        }
}

In this example we used the FileReader package to read the file and used the FileReader class to enable us to read from the file. Then we created the fr object and specified the file path in disk E. We created a variable called i that locates the character via the fr.read() function and as long as it reads data it will keep returning a value other than -1. When you do not find data and finish reading the file, and this is the condition to stop from the loop, it means continue reading as long as the value does not equal -1. After that, we print the data that we obtained, and we convert the location of the character into text data, and then we print it.

An example of an application for studying arrays and text files.

package ioo;
import.java.io.BufferedWriter;
import.java.io.File;
import.java.io.FileWriter;
import.java.io.IOExeption;
public class Ioo {
    public static void main(String[] args) {
        String []st_no={"1","2","3","4"};
        String []st_name={"data","kaissar","saja","wazeer"};
        File f=new File("E: programmertech.txt");
        try{
        BufferedWriter w=new BufferedWriter(new FileWriter(f));
        for(int i=0;i < st_no.length;i++)
        {
            w.write(st_no[i]);
            w.write("  ");
            w.write(st_name[i]);
            w.newLine();
        }
        w.close();
    }catch(IOExeption e) {}
    }
}

Initially, we used four packages in this example, which are the io.BufferedWriter package, which is for adding data to the file, and the io.File package for creating the file and specifying its path. And the io.FileWriter package for writing inside the file and the io.IOExeption package for catching unsupported errors. Then we entered the main program and created an array named st_no to identify the numbers of four students and created a second array st_name for the names of the four students.

Then we started by creating the file via the File class and gave it an object named f, then we specified its path and name. Then we included the BufferedWriter package and gave it an object named w, then we used the FileWriter class and sent it. to the f object of the files and we put them under try and catch as a mandatory option to avoid any error. We entered it with a for loop and started the process of writing data to the file through the w object that belongs to the BufferedWriter class. And then we create the values ​​via w.write until the loop ends and is equal to the length of the array and we use . The newLine function drops a line at the completion of each cycle and then we close the file with w.close.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com