Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
12 kB
3
Indexable
Never
javacore.data

3. file
    3.1 Exercise.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Exercise {

    public static void main(String[] args) {
        //exercise2();


    }

    public static void exercise1() {
        String pathToFile = "C:\\Users\\thieu.bui\\Downloads\\dataset_91033.txt";
        File file = new File(pathToFile);

        int sum = 0;
        try (Scanner scanner2 = new Scanner(file)) {
            while (scanner2.hasNextInt()) {
                sum += scanner2.nextInt();
            }
        } catch (FileNotFoundException e) {
            System.out.println("No file found: " + pathToFile);
        }

        System.out.println(sum);
    }

    public static void exercise2() {
        String pathToFile = "C:\\Users\\thieu.bui\\Downloads\\dataset_91007.txt";
        File file = new File(pathToFile);

        int greatest = 0;
        int num;
        try (Scanner scanner2 = new Scanner(file)) {
            while (scanner2.hasNextInt()) {
                num = scanner2.nextInt();
                if (num > greatest) {
                    greatest = num;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("No file found: " + pathToFile);
        }

        System.out.println(greatest);
    }

    int process(int a, int b) {
        return 0;
    }

    public List<File> getAllFiles(File rootDir) {
        File[] children = rootDir.listFiles();
        if (children == null || children.length == 0) {
            return Collections.emptyList();
        }

        List<File> files = new ArrayList<>();
        for (File child : children) {
            if (child.isDirectory()) {
                files.addAll(getAllFiles(child));
            } else {
                files.add(child);
            }
        }

        return files;
    }
}

################################

    3.2. FileClass.java

import java.io.File;

/*
Objects of the File class are immutable
 */

public class FileClass {

    public static void main(String[] args) {
        System.out.println(File.separator);

        basicMethod();
    }

    public static void path() {
        File absolutePath =  new File("D:\\Materials\\java-materials.pdf");

        File relativePath = new File(".\\images\\picture.jpg");
    }

    public static void basicMethod() {
        File file = new File(".\\Learning\\Java\\LearningJava\\TestFile.txt");

        System.out.println("File name: " + file.getName());
        System.out.println("File path: " + file.getPath());
        System.out.println("Is file: " + file.isFile());
        System.out.println("Is directory: " + file.isDirectory());
        System.out.println("Exists: " + file.exists());
        System.out.println("Parent path: " + file.getParent());
    }
}

##########################################

    3.3. ReadingFile.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class ReadingFile {

    public static void main(String[] args) {
        //usingScanner();

        String pathToFile = "D:\\Learning\\Java\\LearningJava\\TestFile.txt";
        try {
            System.out.println(Files.readAllLines(Paths.get(pathToFile)));
        } catch (IOException e) {
            System.out.println("Cannot read file: " + e.getMessage());
        }
    }

    public static void usingScanner() {
        String pathToFile = "D:\\Learning\\Java\\LearningJava\\TestFile.txt";
        File file = new File(pathToFile);
        // Scanner scanner1 = new Scanner(file); // it throws FileNotFoundException (checked)

        try (Scanner scanner2 = new Scanner(file)) {
            while (scanner2.hasNext()) {
                System.out.print(scanner2.nextLine() + " ");
            }
        } catch (FileNotFoundException e) {
            System.out.println("No file found: " + pathToFile);
        }
    }

    public static String readFileAsString(String fileName) throws IOException {
        return new String(Files.readAllBytes(Paths.get(fileName)));
    }
}

#######################################

    3.4. WritingFile.java

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WritingFile {

    public static void main(String[] args) {
        fileWriter();
    }

    /*
    FileWriter(String fileName);
    FileWriter(String fileName, boolean append);
    FileWriter(File file);
    FileWriter(File file, boolean append);
     */
    public static void fileWriter() {
        File file = new File("D:\\Learning\\Java\\LearningJava\\file.txt");
        try(FileWriter writer = new FileWriter(file)) { // overwrites the file
            writer.write("Hello ");
            writer.write("Java");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        // writer.close() -> tranh memory leak
    }

    /*
    PrintWriter(String fileName);
    PrintWriter(File file);
    PrintWriter(Writer writer).
     */
    public static void printWriter() {
        File file = new File("D:\\Learning\\Java\\LearningJava\\file.txt");
        try (PrintWriter printWriter = new PrintWriter(file)) {
            printWriter.print("Hello"); // prints a string
            printWriter.println("Java"); // prints a string and then terminates the line
            printWriter.println(123); // prints a number
            printWriter.printf("You have %d %s", 400, "gold coins"); // prints a formatted string
        } catch (IOException e) {
            System.out.printf("An exception occurred %s", e.getMessage());
        }
    }
}

#########################################

4. iostream
    4.1. outputstream
    4.2. inputstream
        4.2.1. Exercise.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Exercise {

    public static void main(String[] args) throws Exception {
        readSequenceOfBytes();
    }

    public static void test1() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        // start coding here
        char[] arr = new char[50];
        int number = reader.read(arr);

        for (int i = number - 1; i >= 0; i--) {
            System.out.print(arr[i]);
        }
        reader.close();
    }

    public static void readSequenceOfBytes() throws IOException {
        // input: abc
        // output: 979899

        InputStream inputStream = System.in;
        byte[] bytes = new byte[1024];
        int numberOfBytes = inputStream.read(bytes);

        for (int i = 0; i < numberOfBytes; i++) {
            System.out.print(bytes[i]);
        }
    }
}

####################################

        4.2.2. Main.java

import java.io.*;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        characterStream();
        byteStream();
    }

    /*
    Co nhieu class cho viec doc text -> character input streams: char va string
    vi du: FileReader, CharArrayReader, StringReader,...
     */
    public static void characterStream() {
        try (Reader reader = new FileReader("D:\\Learning\\Java\\LearningJava\\file.txt")) {
            char first = (char) reader.read(); // i
            char second = (char) reader.read(); // n
            char[] others = new char[12];
            int number = reader.read(others); // 10

            System.out.println(first + " " + second);
            System.out.println(Arrays.toString(others));
            System.out.println(number);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        // Mot cach khac de doc text data la doc tung ky tu cho den khi stream dong
        try (FileReader reader = new FileReader("D:\\Learning\\Java\\LearningJava\\file.txt")) {
            int charAsNumber = reader.read();
            while(charAsNumber != -1) {
                char character = (char) charAsNumber;
                System.out.print(character);
                charAsNumber = reader.read();
            }
            System.out.println();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void byteStream() {
        try (FileInputStream inputStream = new FileInputStream("D:\\Learning\\Java\\LearningJava\\file.txt")) {
            byte[] bytes = new byte[5];
            int numberOfBytes = inputStream.read(bytes);
            System.out.println(numberOfBytes); // 5
            System.out.println(Arrays.toString(bytes));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

##################################

5. threads
    5.1. Main.java

public class Main {
	public static void main(String[] args) {
		//Main thread -> luong chinh
		System.out.println("Start");
		
		//Cach 1
		//luong t
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println("Thread 1 > " + i);
				}
			}
		});
		t.start();
		
		//luong t2
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println("Thread 2 > " + i);
				}
			}
		});
		t2.start();
		
		//Cach2
		new Thread(new Runnable() {
			@Override
			public void run() {
				
				
			}
		}).start();
		
		//Lambda
		new Thread(() -> {
			
		}).start();
		
		//.........
		System.out.println("End");
	}
}

######################################

    5.2. Test.java

public class Test {
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Thread main start");
		
		ThreadOne threadOne = new ThreadOne();
		threadOne.start();
		
		ThreadTwo threadTwo = new ThreadTwo();
		//new Thread(threadTwo).start();
		Thread t2 = new Thread(threadTwo);
		t2.start();
		
		System.out.println("Noi luong 1 vao thread main.");
		threadOne.join();
		System.out.println("Noi luong 2 vao thread main.");
		t2.join();
		System.out.println("Thread main stop");
		
		//sau 5s thi khong cho luong chay tiep
//		try {
//			Thread.sleep(5000);
//			threadOne.stop();
//			t2.stop();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
	}
}

#################################

    5.3. Test2.java

public class Test2 {
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Thread main start");
		ThreadOne t1 = new ThreadOne();
		Thread t2 = new Thread(new ThreadTwo(t1));
		
		t1.start();
		t2.start();
		t2.join();
		System.out.println("Thread main stop");
	}
}

###################################

    5.4. ThreadOne.java

public class ThreadOne extends Thread {
	@Override
	public void run() {
		System.out.println("t1 is running");
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread One >> " + i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

#######################################

    5.5. ThreadTwo.java

public class ThreadTwo implements Runnable{
	ThreadOne t1;
	
	//ham tao
	public ThreadTwo() {
		super();
	}

	public ThreadTwo(ThreadOne t1) {
		super();
		this.t1 = t1;
	}
	
	@Override
	public void run() {
		System.out.println("t2 is running");
		try {
			System.out.println("join t1 into t2");
			t1.join();
			System.out.println("t1 finish");
			for (int i = 0; i < 10; i++) {
				System.out.println("Thread Two >> " + i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
Leave a Comment