Xu Hướng 11/2022 # Đọc Ghi File Ms Word Bằng Java Với Apache Poi / 2023 # Top 13 View | Hoisinhvienqnam.edu.vn

Bạn đang xem bài viết Đọc Ghi File Ms Word Bằng Java Với Apache Poi / 2023 được cập nhật mới nhất trên website Hoisinhvienqnam.edu.vn. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất.

Đọc ghi file MS Word bằng Java với Apache POI

Apache POI là một thư viện mã nguồn mở cung cấp bởi apache được sử dụng để xử lý các file office như word, excel, powerpoint…

XWPFDocument:Được sử dụng để đọc ghi các file MS-Word với định dạng .docx (đọc, lưu file, thêm đoạn văn bản…)

XWPFParagraph: Được dùng để tạo đoạn paragraph trong tài liệu word. (Tùy chỉnh căn lề, border)

XWPFRun: Được sử dụng thể thêm text vào paragraph (Tùy chỉnh font, size…)

XWPFTable: Được dùng để thêm mới bảng vào file (Thêm cột, thêm dòng, cài đặt chiều rộng cho cột)

XWPFWordExtractor: Đây là class cơ bản được dùng để lấy text đơn giản từ tài liệu word (lấy tất cả text bên trong file word)

Thư viện sử dụng:

Ví dụ ghi file MS Word:

package stackjava.com.apachepoi.word.demo; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun; public class DemoWrite { public static void main(String[] args) throws IOException { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph1 = document.createParagraph(); XWPFRun run = paragraph1.createRun(); run.setText(“Paragraph 1: stackjava.com”); XWPFParagraph paragraph2 = document.createParagraph(); run = paragraph2.createRun(); run.setText(“Paragraph 2: demo read/write file MS-Word”); FileOutputStream out = new FileOutputStream(new File(“demo-apache-apoi-word.docx”)); document.write(out); out.close(); document.close(); System.out.println(“successully”); }
}

package stackjava.com.apachepoi.word.demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class DemoWrite { public static void main(String[] args) throws IOException { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph1 = document.createParagraph(); XWPFRun run = paragraph1.createRun(); run.setText(“Paragraph 1: stackjava.com”); XWPFParagraph paragraph2 = document.createParagraph(); run = paragraph2.createRun(); run.setText(“Paragraph 2: demo read/write file MS-Word”); FileOutputStream out = new FileOutputStream(new File(“demo-apache-apoi-word.docx”)); document.write(out); out.close(); document.close(); System.out.println(“successully”); } }

Kết quả:

package stackjava.com.apachepoi.word.demo; import java.io.FileInputStream;
import java.util.List; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph; public class DemoRead { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream(“demo-apache-apoi-word.docx”); XWPFDocument document = new XWPFDocument(OPCPackage.open(fis)); for (XWPFParagraph paragraph : paragraphList) { System.out.println(paragraph.getText()); } System.out.println(“==============================”); System.out.println(“Read file using XWPFWordExtractor “); XWPFWordExtractor wordExtractor = new XWPFWordExtractor(document); System.out.println(wordExtractor.getText()); wordExtractor.close(); document.close(); } catch (Exception ex) { ex.printStackTrace(); } }
}

package stackjava.com.apachepoi.word.demo; import java.io.FileInputStream; import java.util.List; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; public class DemoRead { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream(“demo-apache-apoi-word.docx”); XWPFDocument document = new XWPFDocument(OPCPackage.open(fis)); for (XWPFParagraph paragraph : paragraphList) { System.out.println(paragraph.getText()); } System.out.println(“==============================”); System.out.println(“Read file using XWPFWordExtractor “); XWPFWordExtractor wordExtractor = new XWPFWordExtractor(document); System.out.println(wordExtractor.getText()); wordExtractor.close(); document.close(); } catch (Exception ex) { ex.printStackTrace(); } } }

Kết quả:

Paragraph 1: stackjava.com
Paragraph 2: demo read/write file MS-Word
==============================
Read file using XWPFWordExtractor Paragraph 1: stackjava.com
Paragraph 2: demo read/write file MS-Word

Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-Word ============================== Read file using XWPFWordExtractor Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-Word

Okay, Done!

References:

https://poi.apache.org/document/

Do vậy, trong bài viết này, mình đã giới thiệu về Apache POI là một thư viện mã nguồn mở cho phép chúng ta thao tác với các tập tin định dạng microsoft office. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách đọc và ghi excel file sử dụng Apache POI.

Maven denpendency

Để thao tác được với Excel file, chúng ta cần thêm các denpendency cần thiết.

Một số lưu ý khi sử dụng Apache POI

Bài viết này sẽ hướng dẫn các bạn cách đọc và ghi file excel sử dụng thư viện Apache POI. Tuy nhiên có một số lưu ý sau các bạn cần chú ý để có thể triển khai cho từng trường hợp của mình.

Tiền tố HSSF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2003.

Tiền tố XSFF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2007.

XSSFWorkbook và HSSFWorkbook là các class đại diện cho một excel workbook.

HSSFSheet và XSSFSheet là các class đại diện cho một excel WorkSheet.

Row đại diện cho một dòng.

Cell đại diện cho một ô trong một hàng xác định.

Trong bài hướng dẫn này, các bạn sẽ được hướng dẫn cách đọc ghi file excel Microsoft Excel 2007 có đôi là xlsx, có nghĩa là chúng ta sẽ sử dụng các class có tiền tố là XSFF để đọc file exel.

Ghi excel file

Để ghi một excel file cần qua những bước cơ bản sau:

Tạo workbook.

Tạo một sheet trong workbook.

Tạo một dòng trong sheet.

Thêm một cột trong sheet.

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(“student Details”); data.put(“1”, new Object[]{“ID”, “NAME”, “LASTNAME”}); data.put(“2”, new Object[]{1, “Pankaj”, “Kumar”}); data.put(“3”, new Object[]{2, “Prakashni”, “Yadav”}); data.put(“4”, new Object[]{3, “Ayan”, “Mondal”}); data.put(“5”, new Object[]{4, “Virat”, “kohli”}); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { FileOutputStream out = new FileOutputStream(new File(“gfgcontribute.xlsx”)); workbook.write(out); out.close(); System.out.println(“gfgcontribute.xlsx written successfully on disk.”); } catch (Exception e) { e.printStackTrace(); } } }

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(“student Details”); data.put(“1”, new Object[]{“ID”, “NAME”, “LASTNAME”}); data.put(“2”, new Object[]{1, “Pankaj”, “Kumar”}); data.put(“3”, new Object[]{2, “Prakashni”, “Yadav”}); data.put(“4”, new Object[]{3, “Ayan”, “Mondal”}); data.put(“5”, new Object[]{4, “Virat”, “kohli”}); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { FileOutputStream out = new FileOutputStream(new File(“gfgcontribute.xlsx”)); workbook.write(out); out.close(); System.out.println(“gfgcontribute.xlsx written successfully on disk.”); } catch (Exception e) { e.printStackTrace(); } } }

Đọc file excel

Để đọc một excel file chúng ta cũng có các bước sau:

Khởi tạo một workbook instance từ excel file.

Lấy sheet từ workbook.

Đọc từng dòng, mỗi dòng lấy giá trị từ từng cột.

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File(“gfgcontribute.xlsx”)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); while (rowIterator.hasNext()) { Row row = rowIterator.next(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + “t”); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + “t”); break; } } System.out.println(“”); } file.close(); } catch (Exception e) { e.printStackTrace(); } } }

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File(“gfgcontribute.xlsx”)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); while (rowIterator.hasNext()) { Row row = rowIterator.next(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + “t”); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + “t”); break; } } System.out.println(“”); } file.close(); } catch (Exception e) { e.printStackTrace(); } } }

Output:

IDtNAMEtLASTNAMEt1.0tPankajtKumart2.0tPrakashnitYadavt3.0tAyantMondalt4.0tVirattkohlit

Note: Nếu bạn muốn đọc một file tại một đường dẫn khác, thì bạn chỉ việc thay

FileInputStream file = new FileInputStream(new File(“gfgcontribute.xlsx”));

FileInputStream file = new FileInputStream(new File(“gfgcontribute.xlsx”));

thành đường dẫn bạn mong muốn.

Thêm dữ liệu vào sheet

Nếu bạn đã có một excel sẵn và muốn ghi thêm dự liệu vào đó, thì chỉ cần lấy sheet đó ra từ workbook, đi đến dòng cuối cùng và bắt đầu ghi thêm dữ liệu vào.

private static final String FILE_NAME = “C:\Users\pankaj\Desktop\projectOutput\blo.xlsx”; public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue(“xyz”); ….. .. FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); fileOut.close(); }

private static final String FILE_NAME = “C:\Users\pankaj\Desktop\projectOutput\blo.xlsx”; public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue(“xyz”); ….. .. FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); fileOut.close(); }

Nguồn tham khảo

https://www.geeksforgeeks.org/reading-writing-data-excel-file-using-apache-poi/

Khi lập trình với bất cứ hệ thống nào thì việc thao tác với các file excel luôn là điều bắt buộc mọi developer phải nắm được. Và để làm việc hiệu quả với excel file trong java thì tôi xin giới thiệu thư viện Apache POI trong bài viết này. POI là viết tắt của Poor Obfuscation Implementation, đó là một thư viện mã nguồn mở của Java, được cung cấp bởi Apache giúp chúng ta làm việc với các tài liệu của Microsoft như Word, Excel, PowerPoint…

Để thao tác với các file Excel thì POI cung cấp cho chúng ta các khái niệm chính sau:

Workbook: Đây là khái niệm đại diện cho một bảng tính, hay một file Excel.

Sheet: tương đương với các sheet trong file Excel, một workbook có thể có một hoặc nhiều sheet.

Row: đơn vị hàng trong một bảng tính

Cell: đại diện cho một cột trong bảng tính. Như vậy mỗi một ô trong file Excel sẽ được biểu diễn bằng một row và một cell.

Để làm việc với Excel thì chúng ta không cần quan tâm đến tất cả các class trong thư viện POI mà chỉ cần để ý đến 2 loại sau:

Các class có tiếp đầu ngữ là HSSF (Horrible SpreadSheet Format) : Các class giúp đọc và ghi file dang Microsoft Excel (XLS – dạng excel cũ). Ví dụ: HSSFWorkbook, HSSFSheet, HSSFCellStyle,…

Các class có tiếp đầu ngữ là XSSF (XML SpereadSheet Format) : Đọc và ghi định dạng file Open Office XML (XLSX – dạng excel mới).

Nếu bạn sử dụng Maven thì cần thêm dependency của POI vào file pom.xml:

Còn Gradle thì thêm vào build.gradle:

compile “org.apache.poi:poi:3.17”

compile “org.apache.poi:poi:3.17”

Trước tiên, ta tạo một class model để có thể ghi các ra các row theo một List data:

public class Employee { private String name; private String email; private Date dateOfBirth; private double daysOfWork; private double salaryPerDay; private Double totalSalary; public Employee(String name, String email, Date dateOfBirth, double daysOfWork, double salaryPerDay, Double totalSalary) { chúng tôi = name; this.email = email; this.dateOfBirth = dateOfBirth; this.daysOfWork = daysOfWork; this.salaryPerDay = salaryPerDay; this.totalSalary = totalSalary; }

public class Employee { private String name; private String email; private Date dateOfBirth; private double daysOfWork; private double salaryPerDay; private Double totalSalary; public Employee(String name, String email, Date dateOfBirth, double daysOfWork, double salaryPerDay, Double totalSalary) { chúng tôi = name; this.email = email; this.dateOfBirth = dateOfBirth; this.daysOfWork = daysOfWork; this.salaryPerDay = salaryPerDay; this.totalSalary = totalSalary; }

Tiếp đến chuẩn bị data raw để ghi vào file excel:

Sau các bước chuẩn bị data, chúng ta tạo một workbook:

Có workbook rồi chúng ta tạo tiếp một sheet trong đó:

Có thể thêm một chút màu sắc font bạt cho đẹp mắt:

Font headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setFontHeightInPoints((short) 14); headerFont.setColor(IndexedColors.RED.getIndex());

Font headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setFontHeightInPoints((short) 14); headerFont.setColor(IndexedColors.RED.getIndex());

Sau đó chúng ta tạo row đầu tiên chứa các tiêu đề của các cột:

Do trong phần model của chúng ta có loại dữ liệu khác đặc biệt là Date (dateOfBirth) nên chúng ta cần một format cho nó:

Tiếp đến là công việc chính, set data vào các ô trong file excel:

Chú ý rằng cột cuối cùng ta dùng công thức để tính tổng lương của mỗi nhân viên nên CellType ở đây sẽ là FORMULA.

Cuối cùng là ghi tất cả ra một file Excel thật và kết thúc việc tạo một file Excel:

Nội dung file employee.xlsx sẽ như sau:

Để đọc một file Excel có sẵn, đầu tiên chúng ta cũng tạo một workbook cho file đó:

Duyệt các sheet trong một workbook:

Vì trong file excel ta vừa tạo chỉ có một sheet nên chúng ta sẽ get nó ra như sau:

Để duyệt các row trong sheet, ta làm như sau:

Sau khi duyệt xong nhớ đóng workbook lại:

Màn hình console sẽ trông như sau:

Từ đây ta có thể nhận thấy đối với kiểu là FORMULA thì khi in ra chúng ta sẽ nhận được công thức của field đó chứ không phải giá trị cuối cùng. Để nhận các giá trị cuối cùng của field thì chúng ta viết thêm hàm sau:

private static Object getCellValue(Cell cell, FormulaEvaluator evaluator) { CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellTypeEnum()) { case BOOLEAN: return cellValue.getBooleanValue(); case NUMERIC: return cellValue.getNumberValue(); case STRING: return cellValue.getStringValue(); case BLANK: return “”; case ERROR: return cellValue.getError(cell.getErrorCellValue()).getStringValue();

private static Object getCellValue(Cell cell, FormulaEvaluator evaluator) { CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellTypeEnum()) { case BOOLEAN: return cellValue.getBooleanValue(); case NUMERIC: return cellValue.getNumberValue(); case STRING: return cellValue.getStringValue(); case BLANK: return “”; case ERROR: return cellValue.getError(cell.getErrorCellValue()).getStringValue();

Với một cell có kiểu FORMULA bạn có thể in ra công thức của nó và sử dụng FormulaEvaluator để tính toán giá trị của ô cho bởi công thức đó. Sau đó sửa lại đoạn duyệt row như sau:

Kết quả nhận được sẽ như sau:

Để sửa một file Excel thì chúng ta cũng làm tương tự đọc một file Excel. Đầu tiên là tạo một workbook cho nó và một sheet tương ứng:

Workbook workbook = WorkbookFactory.create(new File(“./employee.xlsx”);

Workbook workbook = WorkbookFactory.create(new File(“./employee.xlsx”);

Xác định vị trí cần update lại và định vị nó. Cần chú ý nếu vị trí cần update chưa được tạo thì cần khởi tạo field đó trước, nếu không chương trình sẽ throw một Exception:

Update lại định dạng và giá trị của field đó:

Output ra một file Excel khác và đóng workbook:

https://github.com/tubean/apache-poi-tutorial.git

https://www.callicoder.com/java-write-excel-file-apache-poi/https://www.callicoder.com/java-read-excel-file-apache-poi/

Đọc và ghi file trong java là các hoạt động nhập/xuất dữ liệu (nhập dữ liệu từ bàn phím, đọc dữ liệu từ file, ghi dữ liệu lên màn hình, ghi ra file, ghi ra đĩa, ghi ra máy in…) đều được gọi là luồng (stream).

Đọc và ghi file trong java – Các loại luồng dữ liệu

Bước 1: Tạo đối tượng luồng và liên kết với nguồn dữ liệu.

Bước 2: Thao tác dữ liệu (đọc hoặc ghi hoặc cả hai).

Bước 3: Đóng luồng.

Xử lý nhập xuất dữ liệu sử dụng luồng byte

Sử dụng luồng byte trong các trường hợp như nhập xuất kiểu dữ liệu nguyên thủy (như kiểu int, float, double, boolean), nhập xuất kiểu dữ liệu kiểu đối tượng (object)

Đọc và ghi dữ liệu nhị phân (binary data)

package file_handling; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * * @author chúng tôi */ public class DataOutputExample { public static void main(String[] args) { try {

package file_handling; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * * @author chúng tôi */ public class DataOutputExample { public static void main(String[] args) { try {

Ví dụ 2: Đọc dữ liệu chứa trong tập tin d:/mydata.bin với DataInputStream

package file_handling; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * * @author chúng tôi */ public class DataInputExample { public static void main(String[] args) { try {

package file_handling; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * * @author chúng tôi */ public class DataInputExample { public static void main(String[] args) { try {

Ví dụ 3: Đọc và ghi dữ liệu kiểu object

Tạo lớp Stock và lớp này phải cài đặt giao diện Serializable

package file; import java.io.Serializable; /** * * @author chúng tôi */ public class Stock implements Serializable{ private int id; private String desc; private double price; private int quantity; public Stock(int id, String desc, double price, int quantity) { chúng tôi = id; chúng tôi = desc; this.price = price; this.quantity = quantity; } @Override public String toString() { return id + “-” + desc + “-” + price + “-” + quantity; } }

package file; import java.io.Serializable; /** * * @author chúng tôi */ public class Stock implements Serializable{ private int id; private String desc; private double price; private int quantity; public Stock(int id, String desc, double price, int quantity) { chúng tôi = id; chúng tôi = desc; this.price = price; this.quantity = quantity; } @Override public String toString() { return id + “-” + desc + “-” + price + “-” + quantity; } }

Tạo lớp ObjectOutputExample dùng để ghi dữ liệu kiểu object

package file; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * * @author chúng tôi */ public class ObjectOutputExample { public static void main(String[] args) { try {

package file; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * * @author chúng tôi */ public class ObjectOutputExample { public static void main(String[] args) { try {

Tạo lớp ObjectInputExample dùng để đọc dữ liệu kiểu object

package file; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.ObjectInputStream; /** * * @author chúng tôi */ public class ObjectInputExample { public static void main(String[] args) { try {

package file; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.ObjectInputStream; /** * * @author chúng tôi */ public class ObjectInputExample { public static void main(String[] args) { try {

Xử lý nhập xuất dữ liệu bằng luồng character

Luồng byte rất mạnh mẽ và linh hoạt. Tuy nhiên nếu bạn muốn lưu trữ file chứa văn bản Unicode thì luồng character là lựa chọn tốt nhất vì ưu điểm của luồng character là nó thao tác trực tiếp trên ký tự Unicode.

Tất cả các luồng character đều được kế thừa từ 2 lớp Reader và Writer

Ví dụ 1: Ghi dữ liệu với FileWriter

package file_handling; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * * @author chúng tôi */ public class FileWriterExample { public static void main(String[] args) { try {

package file_handling; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * * @author chúng tôi */ public class FileWriterExample { public static void main(String[] args) { try {

Ví dụ 2: Đọc dữ liệu với FileReader

package file_handling; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; /** * * @author chúng tôi */ public class FileReaderExample { public static void main(String[] args) { try {

package file_handling; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; /** * * @author chúng tôi */ public class FileReaderExample { public static void main(String[] args) { try {

Đọc và ghi file trong java – Thực hành

Tạo package tên file và thực hiện các yêu cầu bên dưới

Bài thực hành số 1: Tạo lớp NhanVien có các thuộc tính mã nhân viên, họ tên, tuổi và lương.

Viết setter, getter, constructor và toString.

Viết phương thức cho phép nhập thông tin cho 3 nhân viên từ bàn phím. Sử dụng FileWriter để ghi thông tin vào nhanvien.txt.

Viết phương thức để đọc nội dung file chúng tôi và in những gì đọc được từ file ra màn hình.

Bài thực hành số 2: Tạo lớp mới và thực hiện các xử lý sau

Viết phương thức tạo mảng 3 nhân viên, nhập thông tin cho các nhân viên, sử dụng ObjectOutputStream để ghi mảng đối tượng nhân viên vào file nhanvien.bin

Viết phương thức để đọc file chúng tôi và in mảng nhân viên ra màn hình.

Cập nhật thông tin chi tiết về Đọc Ghi File Ms Word Bằng Java Với Apache Poi / 2023 trên website Hoisinhvienqnam.edu.vn. Hy vọng nội dung bài viết sẽ đáp ứng được nhu cầu của bạn, chúng tôi sẽ thường xuyên cập nhật mới nội dung để bạn nhận được thông tin nhanh chóng và chính xác nhất. Chúc bạn một ngày tốt lành!