1. 程式人生 > >演算法-(java)-從檔案中讀取、寫入資料

演算法-(java)-從檔案中讀取、寫入資料

1.m的n次冪表示

在演算法題中經常遇到10的n次冪,java中計算中,有一個函式,返回double型別,math.pow(m,n),m為基數,n為冪次方。這樣打印出結果,會打印出帶e的數字,如果想要實際顯示,可用BigDecimal(BigDecimal result=new BigDecimal(Math.pow(10,10)); )表示 。
2.檔案到讀取與寫入

/**
 * Created by 蘇葉 on 16/10/29.
 */
import java.io.*;
public class Factorial {
     /**
      * 功能:Java讀取txt檔案的內容
      * 步驟:1:先獲得檔案控制代碼
      * 2:獲得檔案控制代碼當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
      * 3:讀取到輸入流後,需要讀取生成位元組流
      * 4:一行一行的輸出。readline()。
      * 備註:需要考慮的是異常情況
      * @param
filePath */
public static void readTxtFile(String filePath){ try { String encoding="GBK"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判斷檔案是否存在 InputStreamReader read = new
InputStreamReader( new FileInputStream(file),encoding);//考慮到編碼格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; FileWriter writer; writer = new FileWriter("/Users/suye/project/src/out.txt"
); BufferedWriter bw = new BufferedWriter(writer); while((lineTxt = bufferedReader.readLine()) != null){ try { //寫入檔案 bw.write(lineTxt+"\r\n"); } catch (IOException e) { e.printStackTrace(); } System.out.println(lineTxt); } read.close(); bw.close(); }else{ System.out.println("找不到指定的檔案"); } } catch (Exception e) { System.out.println("讀取檔案內容出錯"); e.printStackTrace(); } } public static void main(String argv[]){ String filePath = "/Users/suye/project/src/in.txt"; readTxtFile(filePath); } }