當前位置:首頁 » 編程語言 » java讀取文件的內容

java讀取文件的內容

發布時間: 2023-07-31 11:11:47

1. java中怎樣從一個文件中讀取文件信息

java讀取文件路徑、所佔空間大小等文件消息,主要是使用FileInputStream類來操作,示例如下:

importjava.io.File;
importjava.io.FileInputStream;

publicclassceshi{
publicstaticvoidmain(String[]args)throwsException{

java.io.FilelocalFile=newFile("D:\1.txt");
FileInputStreamins=newFileInputStream(localFile);
intcountLen=ins.available();
byte[]m_binArray=newbyte[countLen];
ins.read(m_binArray);
ins.close();
System.out.println(localFile.getAbsoluteFile()+""
+localFile.getFreeSpace());
}
}

運行結果如下:

2. java如何讀取整個excel文件的內容

在java程序添加spire.xls.jar依賴

importcom.spire.xls.*;

publicclassReadExcel{
publicstaticvoidmain(String[]args){

//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//遍歷工作表的每一行
for(inti=1;i<sheet.getLastRow()+1;i++){
//遍歷工作的每一列
for(intj=1;j<sheet.getLastColumn()+1;j++){
//輸出指定單元格的數據
System.out.print(sheet.get(i,j).getText());
System.out.print(" ");
}
System.out.print(" ");
}
}
}

3. java如何讀取整個excel文件的內容

本例使用java來讀取excel的內容並展出出結果,代碼如下:

復制代碼 代碼如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ExcelOperate {

public static void main(String[] args) throws Exception {
File file = new File("ExcelDemo.xls");
String[][] result = getData(file, 1);
int rowLength = result.length;
for(int i=0;i<rowLength;i++) {
for(int j=0;j<result[i].length;j++) {
System.out.print(result[i][j]+"\t\t");
}
System.out.println();
}

}
/**
* 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行
* @param file 讀取數據的源Excel
* @param ignoreRows 讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1
* @return 讀出的Excel中數據的內容
* @throws FileNotFoundException
* @throws IOException
*/
public static String[][] getData(File file, int ignoreRows)
throws FileNotFoundException, IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// 打開HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行為標題,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum() + 1;
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
// 注意:一定要設成這個,否則可能會出現亂碼
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 導入時如果為公式生成的數據則無值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
values[columnIndex] = rightTrim(value);
hasValue = true;
}

if (hasValue) {
result.add(values);
}
}
}
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}
return returnArray;
}

/**
* 去掉字元串右邊的空格
* @param str 要處理的字元串
* @return 處理後的字元串
*/
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
}

4. java如何讀取一個txt文件的所有內容

importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;


publicclassH{
/**
*功能:Java讀取txt文件的內容
*步驟:1:先獲得文件句柄
*2:獲得文件句柄當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
*3:讀取到輸入流後,需要讀取生成位元組流
*4:一行一行的輸出。readline()。
*備註:需要考慮的是異常情況
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判斷文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考慮到編碼格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}

}

publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\20121012.txt";
//"res/";
readTxtFile(filePath);
}}

5. java中讀取文件數據

//使用字元流按行讀取
BufferedReaderbr=newBufferedReader(newFileReader("D:\1.txt"));
Stringline=null;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}
br.close();
//輸出讀取到的內容
System.out.println(sb.toString());

6. JAVA中讀取文件(二進制,字元)內容的幾種方

JAVA中讀取文件內容的方法有很多,比如按位元組讀取文件內容,按字元讀取文件內容,按行讀取文件內容,隨機讀取文件內容等方法,本文就以上方法的具體實現給出代碼,需要的可以直接復制使用

public class ReadFromFile {
/**
* 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
// 一次讀一個位元組
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
// 一次讀多個位元組
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以字元為單位讀取文件,常用於讀文本,數字等類型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
// 一次讀一個字元
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
// 但如果這兩個字元分開顯示時,會換兩次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
// 一次讀多個字元
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 讀入多個字元到字元數組中,charread為一次讀取字元數
while ((charread = reader.read(tempchars)) != -1) {
// 同樣屏蔽掉\r不顯示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}

} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以行為單位讀取文件,常用於讀面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 隨機讀取文件內容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("隨機讀取一段文件內容:");
// 打開一個隨機訪問文件流,按只讀方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件長度,位元組數
long fileLength = randomFile.length();
// 讀文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 將讀文件的開始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
// 將一次讀取的位元組數賦給byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}

/**
* 顯示輸入流中還剩的位元組數
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("當前位元組輸入流中的位元組數為:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}

7. java中怎樣從文件中讀取數據

分為讀位元組,讀字元兩種讀法x0dx0a◎◎◎FileInputStream 位元組輸入流讀文件◎◎◎x0dx0apublic class Maintest {x0dx0ax0dx0apublic static void main(String[] args) throws IOException {x0dx0ax0dx0aFile f=new File("G:\\just for fun\\xiangwei.txt");x0dx0ax0dx0aFileInputStream fin=new FileInputStream(f);x0dx0ax0dx0abyte[] bs=new byte[1024];x0dx0ax0dx0aint count=0;x0dx0awhile((count=fin.read(bs))>0)x0dx0a{x0dx0ax0dx0aString str=new String(bs,0,count);//反復定義新變數:每一次都 重新定義新變數,接收新讀取的數據x0dx0ax0dx0aSystem.out.println(str);//反復輸出新變數:每一次都 輸出重新定義的新變數x0dx0a}x0dx0afin.close();x0dx0a}x0dx0a}x0dx0ax0dx0a◎◎◎FileReader 字元輸入流讀文件◎◎◎x0dx0apublic class Maintest {x0dx0apublic static void main(String[] args) throws IOException {x0dx0ax0dx0aFile f=new File("H:\\just for fun\\xiangwei.txt");x0dx0ax0dx0aFileReader fre=new FileReader(f);x0dx0ax0dx0aBufferedReader bre=new BufferedReader(fre);x0dx0ax0dx0aString str="";x0dx0awhile((str=bre.readLine())!=null)//●判斷最後一行不存在,為空x0dx0a{x0dx0aSystem.out.println(str);x0dx0a}x0dx0abre.close();x0dx0a fre.close();x0dx0ax0dx0a}x0dx0ax0dx0a}

熱點內容
帶鎖的鉛筆如何改密碼 發布:2025-02-07 06:18:05 瀏覽:163
ubuntu搭建samba伺服器 發布:2025-02-07 05:52:54 瀏覽:54
小型企業網如何配置可以互通 發布:2025-02-07 05:33:56 瀏覽:243
09年crv哪個配置好 發布:2025-02-07 05:17:31 瀏覽:555
nvm源碼編譯 發布:2025-02-07 05:13:19 瀏覽:126
防偽碼查詢源碼 發布:2025-02-07 05:09:39 瀏覽:769
安卓機的通知在哪裡 發布:2025-02-07 05:09:01 瀏覽:282
密碼74是什麼意思 發布:2025-02-07 05:02:10 瀏覽:47
蘋果es瀏覽器無法連接ftp 發布:2025-02-07 04:59:57 瀏覽:285
javaa和a 發布:2025-02-07 04:58:24 瀏覽:64