Simple example of Java file/directory

import java.io.File;
public class Maker {
    public static void main(String[] args){
        try{
            File dir = new File("dir3");
            dir.mkdir();
            File file = new File(dir,"file3");
            file.createNewFile();
        }catch(Exception x){
 
        }
    }
}

The above is just a too-simple example. The following example shows how to read bytes from FileInputStream.

import java.io.File;
import java.io.FileInputStream;
public class fileInputStream {
    public static void main(String[] args) {
        byte[] data = new byte[1024]; //allocates memory for 1024 bytes
        //be careful about how to declare an array in Java
        int readBytes;
        try {
            File file = new File("testfile");
            file.createNewFile();
            FileInputStream in = new FileInputStream(file);
 
            while ((readBytes = in.read(data)) != -1) {
             //read(byte[] b)
             //Reads some number of bytes from the input stream and stores them into the buffer array b.
                System.out.println("read " + readBytes + " bytes, and placed them into temp array named data");
                System.out.println("data :" + data[123]);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you put some data, it will give the following output:

run:
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 952 bytes, and placed them into temp array named data
BUILD SUCCESSFUL (total time: 2 seconds)

You may also like:

Leave a comment