Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.*;

public class Main {

    public static void main(String[] args) {
        try {
            String s = "Hello world from java2s.com";

            RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

            // write something in the file
            raf.writeUTF(s);

            // set the file pointer at 0 position
            raf.seek(0);

            // create an array equal to the length of raf
            byte[] arr = new byte[(int) raf.length()];

            // read the file
            raf.readFully(arr);

            // create a new string based on arr
            String s2 = new String(arr);

            System.out.println(s2);
            raf.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}