java讀取txt文件內(nèi)容簡單舉例
更新時間:2023年07月25日 10:46:16 作者:ChrisyyGuan
這篇文章主要給大家介紹了關(guān)于java讀取txt文件內(nèi)容簡單舉例的相關(guān)資料,通常我們可以直接通過文件流來讀取txt文件的內(nèi)容,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下
一、問題背景
有一個txt文件,需要按行讀取內(nèi)容,并按逗號分隔

二、上代碼
public class Main {
public static void main(String[] args) throws IOException {
List<Flow> flows = new ArrayList<Flow>();
InputStream f1 = new FileInputStream("./data/flow_test.txt");
InputStreamReader reader = new InputStreamReader(f1);
BufferedReader br = new BufferedReader(reader);
br.readLine(); //讀取第一行且不作處理
String strTmp = "";
while ((strTmp = br.readLine()) != null) {
String[] values = strTmp.split(",");
int flow_id = Integer.parseInt(values[0]), flow_bw = Integer.parseInt(values[1]);
int start = Integer.parseInt(values[2]), cost = Integer.parseInt(values[3]);
Flow flow = new Flow(flow_id, flow_bw, start, cost);
flows.add(flow);
}
br.close();
System.out.println(flows.size());
}
}
class Flow {
private int id; //流id
private int bw; //流帶寬
private int start; //起始時間
private int cost; //發(fā)送時間
public Flow(int id, int bw, int start, int cost) {
this.id = id;
this.bw = bw;
this.start = start;
this.cost = cost;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBw() {
return bw;
}
public void setBw(int bw) {
this.bw = bw;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}三、輸出結(jié)果

共19條數(shù)據(jù),故輸出19。
大家還有什么好的讀取方法嗎(有沒有直接讀取int的方法)?
總結(jié)
到此這篇關(guān)于java讀取txt文件內(nèi)容的文章就介紹到這了,更多相關(guān)java讀取txt文件內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Netty+SpringBoot實現(xiàn)定時后端向前端推送數(shù)據(jù)
這篇文章主要介紹了BIO、NIO、AIO三種Java?IO模型,并探討了如何使用Spring?Boot集成Netty實現(xiàn)后臺向前端推送信息的功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
Java結(jié)構(gòu)型設(shè)計模式中的適配器模式與橋接模式解析
這篇文章主要介紹了Java結(jié)構(gòu)型設(shè)計模式中的適配器模式與橋接模式,結(jié)構(gòu)型設(shè)計模式是從程序的結(jié)構(gòu)上解決模塊之間的耦合問題,需要的朋友可以參考下2016-02-02
JDK12的新特性之CompactNumberFormat詳解
這篇文章主要介紹了JDK12的新特性之CompactNumberFormat,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05

