當前位置:編程學習大全網 - 網站源碼 - Java中如何把壹個文件作為壹個整的字符串讀出?

Java中如何把壹個文件作為壹個整的字符串讀出?

//先在妳要編譯的當前文件夾下建壹個文本,裏面給定妳要寫的內容,文件名為a.txt

public class ReadTest{

public static void main(String[] args){

DataInputStream din = null;

try{

//定義壹個輸入流,把當前文件夾下的a.txt裏的內容以GB2312字符集讀出

InputStreamReader is = new InputStreamReader(new FileInputStream("a.txt"),"GB2312");

String str1 = "";

String str2 = "";

//循環讀每壹個字符,並連接在壹個字符串str1上

int i =-1;

while ((i = is.read()) != -1)

{

char m = (char)i;

str2=str2.valueOf(m);

str1 = str1+str2;

}

//對字符串我還是給妳做了簡單的操作,妳可以根據自己的要求修改

str1 = str1.replaceAll(",","\n");//把所有逗號替換為 換行(標點為全角)

str1 = str1.replaceAll("。","\n");//把所有句號替換為 換行

System.out.println(str1); //打印輸出

}catch(FileNotFoundException e){//異常捕獲

e.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

finally{//最終行為---關閉流~

try{

if (din != null){

din.close();

}

}catch(IOException e){

e.printStackTrace();

}

}

}

};

  • 上一篇:微信朋友圈頭像下怎麽做?
  • 下一篇:魔獸爭霸3秒殺腳本
  • copyright 2024編程學習大全網