Java使用IO流讀取TXT文件


通過BufferedReader讀取TXT文件
window系統默認的編碼是GBK,而IDE的編碼多數為UTF-8,如果沒有規定new InputStreamReader(new FileInputStream(file),“GBK”)為GBK會出現讀取內容亂碼。

//文件路徑
String filePath="C:/Users/Admin/Desktop/products.txt";
File file=new File(filePath);
BufferedReader reader = null;
String tempString = null;
int line =1;
try {
// System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
while ((tempString = reader.readLine()) != null) {
System.out.println("Line"+ line + ":" +tempString);
line ++ ;
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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
讀取TXT文件並保持在List集合
TXT文件內容
商品 價格 類型 數量

創建Product對象

public class Product{
private int id;
private String name;
private int price;
private char type;
private int count;
1
2
3
4
5
6
//將txt文件中的產品對象讀取出來並且封裝成集合對象
private static List<Product> getProductFromTxt(){
List<Product> list=new ArrayList<>();
String filePath="C:/Users/Admin/Desktop/products.txt";
File file=new File(filePath);
BufferedReader reader = null;
String content = null;
int line =1;
try {
// System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
while ((content = reader.readLine()) != null) {
//System.out.println("Line"+ line + ":" +tempString);
String[] arra=content.split(",");
Product product=new Product();
product.setId(line);
product.setName(arra[0]);
product.setPrice(Integer.parseInt(arra[1]));
char[] ch=arra[2].toCharArray();
product.setType(ch[0]);
product.setCount(Integer.parseInt(arra[3]));
list.add(product);
line ++ ;
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
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
其中包含了String轉char

char[] ch=str.toCharArray();
product.setType(ch[0]);
————————————————
版權聲明:本文為CSDN博主「IManiy」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/IManiy/article/details/83834360


免責聲明!

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



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