By GokiSoft.com|
20:08 14/08/2021|
Java Advanced
[Share Code] Tìm hiểu File - FileInputStream & FileOutputStream - BufferedInputStream & BufferedOutStream - ObjectInputStream & ObjectOutputStream - Lập trình Java nâng cao - C2010L
#TestController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson02;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Diep.Tran
*/
public class TestController<E, F, G, H extends Book> {
List<E> dataList1;
List<F> dataList2;
List<G> dataList3;
List<H> dataList4;
public TestController() {
dataList1 = new ArrayList<>();
dataList2 = new ArrayList<>();
dataList3 = new ArrayList<>();
dataList4 = new ArrayList<>();
}
public void addE(E e) {
dataList1.add(e);
}
public void addF(F e) {
dataList2.add(e);
}
public void addG(G e) {
dataList3.add(e);
}
public void addH(H e) {
dataList4.add(e);
}
public void showLength() {
System.out.println("dataList1.size = " + dataList1.size());
System.out.println("dataList2.size = " + dataList2.size());
System.out.println("dataList3.size = " + dataList3.size());
System.out.println("dataList4.size = " + dataList4.size());
}
}
#Test.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson02;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class Test {
public static void main(String[] args) {
//testFile();
//saveFile1();
//saveFile2();
//readFile1();
//readFile2();
//saveBook();
//readBook();
//saveBook2();
readBook2();
}
static void readBook2() {
List<Book> bookList;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("books.dat");
ois = new ObjectInputStream(fis);
bookList = (List<Book>) ois.readObject();
for (Book book : bookList) {
System.out.println(book.getFileLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(ois != null) {
try {
ois.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void saveBook2() {
//Fake data -> nhap du lieu tu ban phim.
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("LAP TRINH C", "APTECH", 100000));
bookList.add(new Book("LAP TRINH HTML/CSS/JS", "APTECH", 200000));
bookList.add(new Book("LAP TRINH BootStrap/jQuery", "APTECH", 150000));
bookList.add(new Book("LAP TRINH SQL Server 2019", "APTECH", 300000));
bookList.add(new Book("LAP TRINH PHP/Laravel", "APTECH", 500000));
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("books.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(bookList);
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(oos != null) {
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void readBook() {
List<Book> bookList = new ArrayList<>();
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("books.txt");
bufferedReader = new BufferedReader(reader);
String line;
bufferedReader.readLine();//Bo qua dong header
while((line = bufferedReader.readLine()) != null) {
Book book = new Book();
book.parseFileLine(line);
bookList.add(book);
}
for (Book book : bookList) {
System.out.println(book.getFileLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void saveBook() {
//Fake data -> nhap du lieu tu ban phim.
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("LAP TRINH C", "APTECH", 100000));
bookList.add(new Book("LAP TRINH HTML/CSS/JS", "APTECH", 200000));
bookList.add(new Book("LAP TRINH BootStrap/jQuery", "APTECH", 150000));
bookList.add(new Book("LAP TRINH SQL Server 2019", "APTECH", 300000));
bookList.add(new Book("LAP TRINH PHP/Laravel", "APTECH", 500000));
//Luu thong tin danh sach book -> vao 1 file txt thi lam nhu the nao?
//B1. Duyet qua cac phan tu trong bookList
//B2. Luu String line = book.toString() -> File
//B3. Dong File
FileOutputStream fos = null;
try {
fos = new FileOutputStream("books.txt", false);
String line = "Name, Author Name, Price\n";
byte[] data = line.getBytes("utf8");
fos.write(data);
for (Book book : bookList) {
line = book.getFileLine();
data = line.getBytes("utf8");
fos.write(data);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void readFile2() {
FileReader reader = null;
BufferedReader bufferedReader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new FileReader("file2.txt");
bufferedReader = new BufferedReader(reader);
String line;
while((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
System.out.println(builder.toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void readFile1() {
FileInputStream fis = null;
StringBuilder builder = new StringBuilder();
try {
fis = new FileInputStream("file2.txt");//ASCII
int code;
while((code = fis.read()) != -1) {
builder.append((char) code);
}
System.out.println(builder.toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void saveFile2() {
//Bai toan: Luu du lieu nhap tu ban phim vao file: file2.txt -> thoat luu khi chuoi nhap vao la 'N'
Scanner scan = new Scanner(System.in);
String line;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("file2.txt", true);
do {
System.out.println("Nhap chuoi can them: ");
line = scan.nextLine();
byte[] data = (line + "\n").getBytes("utf8");
fos.write(data);
} while(!line.equalsIgnoreCase("N"));
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void saveFile1() {
//Bai toan: Luu String vao trong File
String str = "Sinh viên Aptech - 54 Lê Thanh Nghị";
FileOutputStream fos = null;
try {
fos = new FileOutputStream("file1.txt");
byte[] data = str.getBytes("utf8");
fos.write(data);
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void testFile() {
//Ham can ban trong File
File file = new File("test.txt");
if(file.exists()) {
System.out.println("File exist: " + file.getAbsolutePath());
} else {
System.out.println("Not exist");
try {
file.createNewFile();
System.out.println("Create new file successfully!!!");
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Su dung File class -> duyet folder trong may tinh
file = new File("./");
File[] fileList = file.listFiles();
for (File f : fileList) {
if(f.isFile()) {
System.out.println(f.getPath() + " -> File");
} else {
System.out.println(f.getPath() + " -> Folder");
}
}
}
}
#Main.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson02;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Diep.Tran
*/
public class Main {
public static void main(String[] args) {
//Phan 1: Generic
ArrayList<Integer> a1 = new ArrayList<>();
a1.add(12);
a1.add(23);
a1.add(43);
// a1.add("sdsdf");
ArrayList<String> a2 = new ArrayList<>();
a2.add("asd");
a2.add("fsd324");
a2.add("sd4545");
// a2.add(23);
//Cau hoi 1: ArrayList<Integer> & ArrayList<String> => May class object
//Cau hoi 2: Tai a1.add(12) -> dung, a1.add("asd") -> error? tuong tu vs a2.
ArrayList<Book> bookList = new ArrayList<>();
bookList.add(new Book("A", "ABC"));
bookList.add(new Book("B", "ABC"));
TestController<String, String, Integer, Book> testController = new TestController<>();
testController.addE("231");
testController.addE("54");
testController.addE("23");
testController.addH(new Book("A", "ASS"));
testController.showLength();
}
}
#Book.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson02;
import java.io.Serializable;
/**
*
* @author Diep.Tran
*/
public class Book implements Serializable{
String name, authorName;
int price;
public Book(String name, String authorName) {
this.name = name;
this.authorName = authorName;
}
public Book() {
}
public Book(String name, String authorName, int price) {
this.name = name;
this.authorName = authorName;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" + "name=" + name + ", authorName=" + authorName + ", price=" + price + '}' + "\n";
}
public String getFileLine() {
return name + ", " + authorName + ", " + price + "\n";
}
public void parseFileLine(String line) {
String[] params = line.split(", ");
name = params[0];
authorName = params[1];
price = Integer.parseInt(params[2]);
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)