導航:首頁 > 文件教程 > java中讀取文件時部分的讀

java中讀取文件時部分的讀

發布時間:2025-06-04 11:42:18

java 讀取 TXT 文件中的內容

在Java中讀取TXT文件內容,可以使用FileInputStream類讀取文件,再通過 InputStreamReader類將其轉換為可讀取的字元流,接著使用BufferedReader類進行逐行讀取。具體代碼如下:

首先創建FileInputStream對象,使用File類指定文件路徑,例如:

FileInputStream fis = new FileInputStream(new File(path));

接著,創建一個InputStreamReader對象,將FileInputStream作為參數傳遞給它:

InputStreamReader isr = new InputStreamReader(fis);

然後,利用BufferedReader對字元流進行處理:

BufferedReader br = new BufferedReader(isr);

為了存儲每一行讀取的內容,我們定義一個字元串變數str:

String str = "";

使用while循環來讀取文件中的每一行,直到沒有更多的行為止。在循環內部,使用readLine()方法讀取一行,並將其賦值給str變數:

while((str=br.readLine())!=null){

System.out.println(str);

}

這個循環會持續執行,直到讀取到文件的最後一行。每次循環中,readLine()方法會讀取一行文本,並將其存儲在str變數中,然後將str的值列印出來。當readLine()返回null時,表示文件讀取完畢,循環結束。

需要注意的是,使用完這些對象後,應該確保關閉它們以釋放資源。可以使用try-with-resources語句來自動完成關閉操作,如下所示:

try (FileInputStream fis = new FileInputStream(new File(path));

InputStreamReader isr = new InputStreamReader(fis);

BufferedReader br = new BufferedReader(isr);) {

String str = "";

while((str=br.readLine())!=null){

System.out.println(str);

}

}

這樣可以確保在讀取文件過程中,資源得到及時釋放,避免資源泄露。

以上就是使用Java讀取TXT文件內容的完整步驟,包括創建文件流對象、讀取文件內容以及處理讀取到的數據。

Ⅱ Java讀入一個txt文件,並且從txt文件中的某一個單詞開始讀裡面的數字

publicstaticvoidmain(String[]args){

Filefile=newFile("D:/123456.txt");

BufferedReaderreader=null;

StringtempString=null;

intline=1;

try{

System.out.println("以行為單位讀取文件內容,一次讀一整行:");

StringBuffersb=newStringBuffer(0);

reader=newBufferedReader(newFileReader(file));

while((tempString=reader.readLine())!=null){

System.out.println("Line"+line+":"+tempString);

intstart=tempString.indexOf("begin");

intend=tempString.indexOf("end");

if(start>-1){

if(end>-1){

sb.append(tempString.substring(start+"begin".length(),end));

}else{

sb.append(tempString.substring(tempString.indexOf("begin"),tempString.length()));

}

}if(start>-1&&end==-1){

sb.append(tempString.substring(0,end));

}line++;

}System.out.println(sb.toString());

reader.close();

}catch(FileNotFoundExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

if(reader!=null){

try{

reader.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

}

}

}
運行結果:
以行為單位讀取文件內容,一次讀一整行:
Line1:
123213okok12412551

Ⅲ java 讀取excel文件 我需要去讀到每一行的每一個數據。 然後操作一番。 最後生成一個XML文件

jxl

package com.cj.fw.xml;
import java.io.File;import java.io.IOException;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;import jxl.WorkbookSettings;import jxl.read.biff.BiffException;import jxl.write.Label;import jxl.write.WritableCell;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;import jxl.write.WriteException;import com.cj.pro.domain.Drilling;
public class DrillingExport {
// 模板文件位置 private final static String TempletFile = "/attachments/template/emergencydrill.xls"; // 數據 private Drilling log = null; private String leixing=null;
/** * 構造函數 */ public DrillingExport( Drilling log,String leixing) { this.log=log; this.leixing=leixing; }
/** * 安全培訓日誌導出表 * @throws IOException * @throws BiffException * @throws WriteException */ public boolean export(HttpServletRequest request,HttpServletResponse response) throws BiffException, IOException, WriteException { String fileName=""; if("1".equals(leixing)){ fileName="應急演練信息導出表.xls"; }else if("2".equals(leixing)){ fileName="消防演練演練信息導出表.xls"; } response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-type","application/file"); response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" )); File file = new File(request.getSession().getServletContext().getRealPath(TempletFile)); WorkbookSettings workbookSettings=new WorkbookSettings(); workbookSettings.setEncoding("ISO-8859-1"); //關鍵代碼,解決中文亂碼 Workbook workbook = Workbook.getWorkbook(file,workbookSettings); WritableWorkbook wwb = Workbook.createWorkbook(response.getOutputStream(), workbook); WritableSheet ws = wwb.getSheet(0); WritableCell cell = null; if("1".equals(leixing)){ cell = new Label(1,0,"應急演練單",ws.getCell(1,0).getCellFormat()); ws.addCell(cell); }else if("2".equals(leixing)){ cell = new Label(1,0,"消防演練單",ws.getCell(1,0).getCellFormat()); ws.addCell(cell); } if(log!=null){ cell = new Label(2,1,log.getRiqi(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); cell = new Label(5,1,log.getDidian(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); cell = new Label(2,2,log.getMingcheng(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); cell = new Label(5,2,log.getZudanwei(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); cell = new Label(2,3,log.getJiaoben(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); cell = new Label(2,4,log.getBeizhu(),ws.getCell(1,1).getCellFormat()); ws.addCell(cell); }else{ cell = new Label(2,4,"導出出錯",ws.getCell(1,0).getCellFormat()); ws.addCell(cell); } //合計小寫 wwb.write(); wwb.close(); workbook.close(); return true; }
}

上面的是導出 你可以變變

Ⅳ java讀取文件每一行

java循環問題,讀文件的每一行

可以通過BufferedReader流的形式進行讀取,之後循環輸出每一行的內容。

BufferedReaderbre=null;

try{

Stringfile="D:/test/test.txt";

bre=newBufferedReader(newFileReader(file));//file為文件的路徑+文件名稱+文件後綴

while((str=bre.readLine())!=null)//●判斷最後一行不存在,為空結束循環

{

System.out.println(str);//原樣輸出讀到的內容

};

備註:流用完之後必須close掉,如上面的就應該是:bre.close();

Java中如何一行行地讀文件

import?java.io.BufferedReader;

import?java.io.File;

import?java.io.FileReader;

import?java.io.IOException;

import?java.io.InputStreamReader;

public?class?ReadTest?{

public?static?void?main(String[]?args)?{

//?讀控制台輸入的文字!

BufferedReader?br?=?null;

String?str?=?null;

try?{

br?=?new?BufferedReader(new?InputStreamReader(System.in));

while?(true)?{

str?=?br.readLine();

if?(str.equals("886"))

break;

System.out.println(str);

}

//?讀文本文件..

br?=?new?BufferedReader(new?FileReader(new?File("C:\Users\Administrator\Desktop\地址.txt")));

for?(str?=?br.readLine();?str?!=?null;?str?=?br.readLine())?{

//列印你讀的文本數據!

System.out.println(str);

}

}?catch?(IOException?e)?{

e.printStackTrace();

}

}

}

核心就是:readLine()方法,一行一行的讀!

java怎麼讀入文件,並逐行輸出

java讀入文件,並逐行輸出,先在D://home建立個文件夾,然後創建一個a.txt文件,然後編輯文件,文本編輯的編碼是utf-8,然後用流逐行讀取輸出,如下:

import?java.io.BufferedInputStream;

import?java.io.BufferedReader;

import?java.io.File;

import?java.io.FileInputStream;

import?java.io.InputStream;

import?java.io.InputStreamReader;

public?class?TestC?{

public?static?void?main(String[]?args){

//獲取要讀取的文件

?File?readFile=new?File("D://home/a.txt");

?//輸入IO流聲明

????????InputStream?in=null;

????????InputStreamReader?ir=null;

????????BufferedReader?br=null;

????????

????????try?{

????????//用流讀取文件

in=new?BufferedInputStream(new?FileInputStream(readFile));

//如果你文件已utf-8編碼的就按這個編碼來讀取,不然又中文會讀取到亂碼

ir=new?InputStreamReader(in,"utf-8");

//字元輸入流中讀取文本,這樣可以一行一行讀取

br=new?BufferedReader(ir);

String?line="";

//一行一行讀取

while((line=br.readLine())!=null){

System.out.println(line);

}

????????}?catch?(Exception?e)?{

e.printStackTrace();

}finally{

//一定要關閉流,倒序關閉

try?{

if(br!=null){

br.close();

}

if(ir!=null){

ir.close();

}

if(in!=null){

in.close();

}

}?catch?(Exception?e2)?{

}

}

????

}

}

結果:

helloworld

您好

123456

java讀取txt文件每一行多少個位元組

import?java.io.File;

import?java.io.RandomAccessFile;

/**

?*?2016年8月31日下午7:00:37

?*?

?*?@author?3306?TODO?計算位元組數

?*

?*/

public?class?FileUtil?{

????public?static?void?main(String[]?args)?{

????????String?filePath?=?"d:/test.txt";//?d盤必須存在test.txt文件

????????readEachLine(filePath);

????}

????/**

?????*?列印文件每一行的位元組數

?????*?

?????*?@param?filePath

?????*????????????文件路徑

?????*/

????private?static?void?readEachLine(String?filePath)?{

????????try?{

????????????File?file?=?new?File(filePath);

????????????if?(file.exists())?{//?文件存在

????????????????RandomAccessFile?accessFile?=?new?RandomAccessFile(file,?"r");//?只賦予讀的許可權

????????????????String?line?=?"";

????????????????long?lineIndex?=?1;

????????????????while?(null?!=?(line?=?accessFile.readLine()))?{

????????????????????System.out.println("line"?+?(lineIndex++)?+?":?"?+?line.getBytes().length);//?列印行號和位元組數

????????????????}

????????????????accessFile.close();

????????????}

????????}?catch?(Exception?e)?{

????????????e.printStackTrace();

????????}

????}

}

Ⅳ java 讀取csv文件里指定行列的值,比如讀取第三行第二列的值。

import java.io.BufferedReader;
import java.io.FileReader;
public class Test {
public void test(int row,int col){
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\a.csv"));//換成你的文件名
// reader.readLine();//第一行信息,為標題信息,不用,如果需要,注釋掉
String line = null;
int index=0;
while((line=reader.readLine())!=null){
String item[] = line.split(" ");//CSV格式文件為逗號分隔符文件,這里根據逗號切分
if(index==row-1){
if(item.length>=col-1){
String last = item[col-1];//這就是你要的數據了
System.out.println(last);
}
}
//int value = Integer.parseInt(last);//如果是數值,可以轉化為數值
index++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Test test = new Test();
test.test(3, 2);
}
}

你的數據格式有問題,空格的個數不確定,沒辦法每行用空格分隔。以下是我調整後的數據格式每行的數據以一個空格分隔,test方法傳入的參數一次是,行,列:

1電機1

2WBS2

3PID3

4CP

5社供出

6原価実績

7社供WC

8外注費

9直材費

10自家製品

11直経費

12その他

13注殘

14注殘

閱讀全文

與java中讀取文件時部分的讀相關的資料

熱點內容
微信群聊無法語音通話 瀏覽:518
魅族微信不會提醒 瀏覽:848
solidworks文件修改路徑 瀏覽:81
微信圖片打包怎麼做文件夾 瀏覽:793
linux復制出文件 瀏覽:225
u盤啟動盤製作工具mac 瀏覽:480
小花喵水深火熱什麼網站能看 瀏覽:138
蘋果5s屏幕鎖密碼忘記 瀏覽:400
怎麼使用郵箱發文件 瀏覽:926
狼人殺白狼王版本技巧 瀏覽:378
word2003怎麼自動生成論文目錄 瀏覽:404
怎麼實現眾多網站跳轉 瀏覽:71
office2010隻安裝word 瀏覽:901
注冊文件dao350dll失敗 瀏覽:228
手機里dslog2txt文件 瀏覽:844
java6sdk 瀏覽:472
qq的文件怎麼改名字怎麼改回來嗎 瀏覽:310
主板不能裝驅動程序 瀏覽:681
教學網站如何開通課程 瀏覽:258
蘋果12手機蜂窩數據怎麼設置 瀏覽:899

友情鏈接