java 保存和讀取本地json文件


保存數據到本地文件


   
   
  
  
          
  1. private void saveDataToFile(String fileName,String data) {
  2. BufferedWriter writer = null;
  3. File file = new File( "d:\\"+ fileName + ".json");
  4. //如果文件不存在,則新建一個
  5. if(!file.exists()){
  6. try {
  7. file.createNewFile();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. //寫入
  13. try {
  14. writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file, false), "UTF-8"));
  15. writer.write(data);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } finally {
  19. try {
  20. if(writer != null){
  21. writer.close();
  22. }
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. System.out.println( "文件寫入成功!");
  28. }


取數據


   
   
  
  
          
  1. private String getDatafromFile(String fileName) {
  2. String Path= "d:\\" + fileName+ ".json";
  3. BufferedReader reader = null;
  4. String laststr = "";
  5. try {
  6. FileInputStream fileInputStream = new FileInputStream(Path);
  7. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
  8. reader = new BufferedReader(inputStreamReader);
  9. String tempString = null;
  10. while ((tempString = reader.readLine()) != null) {
  11. laststr += tempString;
  12. }
  13. reader.close();
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. } finally {
  17. if (reader != null) {
  18. try {
  19. reader.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
  25. return laststr;
  26. }





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM