Announcement

Collapse
No announcement yet.

[Java Tutorial] File Operations (Read & Write)

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • [Java Tutorial] File Operations (Read & Write)

    Setting Up
    To run this program and test it, create a new Java Project inside of Eclipse for Java Developers. Then, create two classes (files), one called Main.java and another called FileOperations.java. Then paste the code below into the corresponding files.

    FileOperations.java:
    Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    
    public class FileOperations {
    
        public void read(String fileName) throws Exception {
            File file = new File(fileName); [COLOR=#c0392b]// Create an object for the file.[/COLOR]    
            FileReader fr = new FileReader(file); [COLOR=#c0392b]// Create an object to read the file.[/COLOR]
            BufferedReader br = new BufferedReader(fr); [COLOR=#c0392b]// Use the FileReader fr with a buffer. Enables line reading instead of character by character reading.[/COLOR]
            String line; [COLOR=#c0392b]// Create a variable to store the current line of the file.[/COLOR]
            while ((line = br.readLine()) != null) { [COLOR=#c0392b]// Set line variable to the current line.[/COLOR]
                System.out.println(line); [COLOR=#c0392b]// Print out the line variable.[/COLOR]
            }
            br.close(); [COLOR=#c0392b]// Clean up memory because br is not used anymore.[/COLOR]
        }
    
        public void write(String fileName, String toWrite) throws Exception {
            File file = new File(fileName); [COLOR=#c0392b]// Create an object for the file.[/COLOR]
            if (!file.exists()) {[COLOR=#c0392b] // If the file does NOT exist (! means not).[/COLOR]
                file.createNewFile();
            }        
            FileWriter fw = new FileWriter(file); [COLOR=#c0392b]// Create an object to write to the file.[/COLOR]
            fw.write(toWrite); [COLOR=#c0392b]// Write a String to the file.[/COLOR]
            fw.close();[COLOR=#c0392b] // Clean up.[/COLOR]
        }
    
        public void writeArray(String fileName) throws Exception {
            File file = new File(fileName); [COLOR=#c0392b]// Create an object for the file.[/COLOR]
            if (!file.exists()) {[COLOR=#c0392b] // If the file does NOT exist (! means not).[/COLOR]
                    file.createNewFile();
            }
            FileWriter fw = new FileWriter(file); [COLOR=#c0392b]// Create an object to write to the file.[/COLOR]
            Object[] stuffToWrite = { "SlashScape", "Zaridias", 762, true, 99.0002345 }; [COLOR=#c0392b]// These are random elements I came up with to write to our file.[/COLOR]
            for (int i = 0; i < stuffToWrite.length; i++) { [COLOR=#c0392b]// Start at 0. Count until the length of the array. Increment by 1 each time.[/COLOR]
                fw.write(stuffToWrite[i].toString()); [COLOR=#c0392b]// Write a String to the file. We can't write objects, so use toString() conversion function.[/COLOR]
                fw.write("\n"); [COLOR=#c0392b]// Write a new line after.[/COLOR]
            }
            fw.close(); [COLOR=#c0392b]// Clean up.[/COLOR]
        }
    
    }
    Main.java:
    Code:
    public class Main {
    
        public static void main(String[] args) {
            FileOperations fo = new FileOperations();
            try {
                fo.write("input.txt", "meow"); [COLOR=#c0392b]// Write "meow" to input.txt.[/COLOR]
                fo.read("input.txt"); [COLOR=#c0392b]// Print the contents of input.txt.[/COLOR]
                fo.writeArray("input.txt"); [COLOR=#c0392b]// Write an array of different data types to input.txt.[/COLOR]
                fo.read("input.txt");[COLOR=#c0392b] // Print the contents of input.txt.[/COLOR]
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    Program Output:
    Code:
    meow
    SlashScape
    Zaridias
    762
    true
    99.0002345
    Explanation:
    A method (AKA a function) is a unit of code grouped together to accomplish a specific task. When dealing with input/output operations, there is a chance of failure. Operations can fail for one reason or another (ie: file does not exist), so to deal with that chance, we throw an exception, or we can put our code (if failure is possible) into a try/catch block.

    A try catch block "tries" something, and if it doesn't work, it catches the Exception, or the reason WHY it didn't work. We can handle failures inside of the catch block, which executes upon failure of the code.
    Last edited by Chris; 03-26-2021, 06:39 AM.
    Don't forget, you can vote every day and it really helps us advertise.

  • #2
    Java is known as a "strongly typed language", this means we have to specify what type each variable is before we can use it. The most basic way to create a variable is by defining the type first and specifying a name to "grab" the data by from memory. Memory can be though of as a giant piece of grid-paper. So in order to use a piece of data from the paper, we call its name for Java to look it up from the paper.

    Here is how you define a variable for the first time:
    Code:
    int number; [COLOR=#c0392b]// type name[/COLOR]
    After it is defined, we don't have to specify the type anymore, because the type will never change after the variable is originally defined. We can call the variable's name and Java will grab it for use:
    Code:
    number = 5; [COLOR=#c0392b]// name = value[/COLOR]
    Think of programming in general as an assembly line with a big claw-hand for manipulating data. The memory is the assembly line and the claw-hand is our processor, which can manipulate data variables and put it back on the assembly line for further modifications. When we create a method, the whole method will be loaded into the processor to accomplish a specific task on the assembly line. Then once the method is done executing (top to bottom), we'll have the current product on the assembly line to pass down to the next part of the assembly line, which will be another method. This process continues until there are no more modifications to be made and our program exits.

    The above example is for primative data types, or simple numeric data essentially. We can also create user defined objects, and Java has some built-in user defined objects as well such as File, FileReader, FileWriter, and thousands more. The syntax for defining a user-defined object variable is the same as above, but the data types are different. Compare and contrast the code below with the code above, you should notice the syntax is the exact same, even though we are dealing with different types of data:
    Code:
    File file; [COLOR=#c0392b]// type name[/COLOR]
    Code:
    file = new File(fileName); [COLOR=#c0392b]// name = value[/COLOR]
    Notice how in both examples, I only defined the type of the data one time. After this one time, I never have to redefine what type the data is, it will never change.

    There is one difference between the two examples. The File object takes what is called a parameter "fileName". This parameter is user-defined, because in order to create a file, we have to specify a name. The fileName is an essential part to any file, so the creators of the File object expect us to provide a name in parenthesis. This isn't done for ints, because ints aren't files and ints do not have fileNames like files do.

    We will cover user-defined classes (objects) soon in another lesson.
    Last edited by Chris; 03-26-2021, 02:14 AM.
    Don't forget, you can vote every day and it really helps us advertise.

    Comment


    • #3
      Every program in Java has to have a main method. The main method is the starting point for the program, it is the first code executed (top to bottom) when the program is run, and all other code stems from the main method like how a tree has a root and then branches from the root. The main method syntax is pretty much the same for every Java program.

      Code:
      public static void main(String[] args) {
          // Code here will execute first when the program is run. This method can call more methods into execution.
      }
      Don't worry what all this means (yet), just know that this code is needed for every program as the entry point.

      Challenge: Create a program from scratch that adds two variables together and prints out the sum of two numbers. See if you can write the sum to a file, and then read the file in order to print the result onto the screen. Remember the assembly line analogy.
      Last edited by Chris; 03-27-2021, 09:59 AM.
      Don't forget, you can vote every day and it really helps us advertise.

      Comment

      Working...
      X