今天在做數據結構的作業時,用到了文件的數據存儲與讀取,當時由於距離上次寫這方面的代碼時間有點長了,有點懵,所以決定這次老老實實的寫篇博客記錄一下:
1 package 數據結構第二階段幼兒評測; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileReader; 6 import java.io.FileWriter; 7 8 9 public class Secondlevel { 10 11 private static double[] dArrs; 12 13 public static void main(String[] args) { 14 15 System.out.println("文件測試數據如下"); 16 try { 17 double[] file = getFile("數據結構第二階段.txt"); 18 19 for(int i=0;i<file.length;i++) { 20 21 System.out.print(file[i]+" "); 22 23 } 24 } catch (Exception e) { 25 // TODO Auto-generated catch block 26 e.printStackTrace(); 27 } 28 29 System.out.println(); 30 System.out.println("正在寫入文件數據......"); 31 try { 32 toFile("inputFile.txt"); 33 } catch (Exception e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } 37 38 } 39 40 //從文件中讀取數據 41 private static double[] getFile(String pathName) throws Exception { 42 //【1】先創建一個File的實體對象 43 File file = new File(pathName); 44 if (!file.exists()) 45 throw new RuntimeException("找不到文件!"); 46 //【2】加載BUfferedReader流 47 BufferedReader br = new BufferedReader(new FileReader(file)); 48 String str; 49 50 //【3】一行一行讀取 51 while ((str = br.readLine()) != null) { 52 53 int s = 0; 54 //文件中數據的分割我用的是‘,’具體根據自己的情況調用下面的split()函數 55 String[] arr = str.split(","); 56 57 dArrs = new double[arr.length]; 58 for(int i=0;i<arr.length;i++) { 59 String string=arr[i]; 60 int parseInt = Integer.parseInt(string); 61 dArrs[i]=parseInt; 62 63 } 64 } 65 return dArrs ; 66 } 67 68 //將數據存儲到文件中 69 private static void toFile(String path) throws Exception{ 70 File file=null; 71 FileWriter fWriter=null; 72 file=new File(path); 73 try { 74 if(!file.exists()) { 75 System.out.println("要讀入數據的文件不存在"); 76 } 77 fWriter=new FileWriter(file); 78 fWriter.write(String.valueOf(dArrs[0])); 79 fWriter.flush(); 80 System.out.println("寫入數據成功!"); 81 }catch (Exception e) { 82 // TODO: handle exception 83 e.printStackTrace(); 84 }finally { 85 if (fWriter!=null) { 86 fWriter.close(); 87 } 88 } 89 90 91 92 } 93 }