ใน Java วิธีการบันทึกและโหลดข้อมูลจากไฟล์ – Simple Production Ready Utility for File I/O Read-Write Operation
เผยแพร่แล้ว: 2020-10-11
ฉันจะเขียนวัตถุลงในไฟล์และอ่านกลับได้อย่างไร
Java นั้นยอดเยี่ยมมากด้วย API จำนวนมาก และด้วย Java 8 เราเปิดใช้งานอย่างสมบูรณ์ด้วย API อื่นๆ มากมาย เช่น Lambda, การอ้างอิงเมธอด, เมธอดเริ่มต้น, อินเทอร์เฟซประเภทที่ดีกว่า, คำอธิบายประกอบซ้ำ, การสะท้อนพารามิเตอร์เมธอด และอื่นๆ อีกมากมาย
เมื่อก่อนฉันได้เขียนบทความเกี่ยวกับวิธีอ่านวัตถุ JSON จากไฟล์ใน Java เป็นการดำเนินการอ่านจาวาอย่างง่าย แต่ในบทช่วยสอนนี้ เราจะ save and load
ข้อมูลจากไฟล์ด้วย Production Ready Java Utility อย่างง่าย

เราไม่เพียงแค่บันทึกวัตถุอย่างง่าย แต่เราจะสร้าง Java POJO อย่างง่ายประเภท CrunchifyCompany และจะไปบันทึกและเรียกวัตถุโดยใช้ GSON
คุณต้องการการพึ่งพาด้านล่างเพื่อให้โปรแกรมด้านล่างทำงาน
ใส่การพึ่งพาโครงการ maven ของคุณด้านล่าง หากคุณมี Dynamic Web Project และต้องการแปลงเป็นโครงการ Maven ให้ทำตามขั้นตอนเหล่านี้
1 2 3 4 5 |
< dependency > < groupId > com . google . code . gson < / groupId > < artifactId > gson < / artifactId > < version > 2.3 < / version > < / dependency > |
นี่คือกระแส:
- สร้างคลาส
CrunchifyReadWriteUtilityForFile.java
- สร้าง
CrunchifyCompany
ภายในคลาสส่วนตัวด้วยสองช่อง-
employees
int ส่วนตัว ; -
companyName
สตริง ส่วนตัว ชื่อ ;
-
- สร้างวัตถุ
crunchify
ภายในวิธีการหลัก - แปลงวัตถุเป็น
Gson
เพื่อให้บันทึกเป็นไฟล์ - ใช้วิธี
crunchifyWriteToFile
เพื่อบันทึกข้อมูลลงในไฟล์ใน Java - ใช้วิธี
crunchifyReadFromFile
เพื่อดึงข้อมูลจากไฟล์ใน Java
นี่คือตัวอย่างที่สมบูรณ์:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
package crunchify . com . tutorial ; import com . google . gson . Gson ; import com . google . gson . stream . JsonReader ; import java . io . * ; import java . nio . charset . StandardCharsets ; /** * @author Crunchify.com * Best and simple Production ready utility to save/load * (read/write) data from/to file */ public class CrunchifyReadWriteUtilityForFile { private static final String crunchifyFileLocation = "/Users/appshah/Documents/crunchify.txt" ; private static final Gson gson = new Gson ( ) ; // CrunchifyComapny Class with two fields // - Employees // - CompanyName private static class CrunchifyCompany { private int employees ; private String companyName ; public int getEmployees ( ) { return employees ; } public void setEmployees ( int employees ) { this . employees = employees ; } public String getCompanyName ( ) { return companyName ; } public void setCompanyName ( String companyName ) { this . companyName = companyName ; } } // Main Method public static void main ( String [ ] args ) { CrunchifyCompany crunchify = new CrunchifyCompany ( ) ; crunchify . setCompanyName ( "Crunchify.com" ) ; crunchify . setEmployees ( 4 ) ; // Save data to file crunchifyWriteToFile ( gson . toJson ( crunchify ) ) ; // Retrieve data from file crunchifyReadFromFile ( ) ; } // Save to file Utility private static void crunchifyWriteToFile ( String myData ) { File crunchifyFile = new File ( crunchifyFileLocation ) ; // exists(): Tests whether the file or directory denoted by this abstract pathname exists. if ( ! crunchifyFile . exists ( ) ) { try { File directory = new File ( crunchifyFile . getParent ( ) ) ; if ( ! directory . exists ( ) ) { // mkdirs(): Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. // Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. directory . mkdirs ( ) ; } // createNewFile(): Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. // The check for the existence of the file and the creation of the file if it does not exist are a single operation // that is atomic with respect to all other filesystem activities that might affect the file. crunchifyFile . createNewFile ( ) ; } catch ( IOException e ) { crunchifyLog ( "Exception Occurred: " + e . toString ( ) ) ; } } try { // Convenience class for writing character files FileWriter crunchifyWriter ; crunchifyWriter = new FileWriter ( crunchifyFile . getAbsoluteFile ( ) , true ) ; // Writes text to a character-output stream BufferedWriter bufferWriter = new BufferedWriter ( crunchifyWriter ) ; bufferWriter . write ( myData . toString ( ) ) ; bufferWriter . close ( ) ; crunchifyLog ( "Company data saved at file location: " + crunchifyFileLocation + " Data: " + myData + "\n" ) ; } catch ( IOException e ) { crunchifyLog ( "Hmm.. Got an error while saving Company data to file " + e . toString ( ) ) ; } } // Read From File Utility public static void crunchifyReadFromFile ( ) { // File: An abstract representation of file and directory pathnames. // User interfaces and operating systems use system-dependent pathname strings to name files and directories. File crunchifyFile = new File ( crunchifyFileLocation ) ; if ( ! crunchifyFile . exists ( ) ) crunchifyLog ( "File doesn't exist" ) ; InputStreamReader isReader ; try { isReader = new InputStreamReader ( new FileInputStream ( crunchifyFile ) , StandardCharsets . UTF_8 ) ; JsonReader myReader = new JsonReader ( isReader ) ; CrunchifyCompany company = gson . fromJson ( myReader , CrunchifyCompany . class ) ; crunchifyLog ( "Company Name: " + company . getCompanyName ( ) ) ; int employee = company . getEmployees ( ) ; crunchifyLog ( "# of Employees: " + Integer . toString ( employee ) ) ; } catch ( Exception e ) { crunchifyLog ( "error load cache from file " + e . toString ( ) ) ; } crunchifyLog ( "\nCompany Data loaded successfully from file " + crunchifyFileLocation ) ; } private static void crunchifyLog ( String string ) { System . out . println ( string ) ; } } |
เอาต์พุตคอนโซล Eclipse:
1 2 3 4 5 6 |
Company data saved at file location : / Users / appshah / Documents / crunchify . txt Data : { "employees" : 4 , "companyName" : "Crunchify.com" } Company Name : Crunchify . com # of Employees: 4 Company Data loaded successfully from file / Users / appshah / Documents / crunchify . txt |
นี่คือเนื้อหาไฟล์ crunchify.txt
ขณะที่ฉันรันโปรแกรม two times
คุณจะเห็นที่นี่ JSONObject สองครั้ง เนื่องจากเรากำลังเพิ่มค่าลงในไฟล์ crunchify.txt

