當前位置:首頁 » 編程語言 » javafile讀取

javafile讀取

發布時間: 2022-08-20 09:47:37

『壹』 java中如何通過file程序去讀取查詢文件中的文件

File類有兩個常用方法可以得到文件路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以通過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。下面是一個具體例子: public class PathTest{ publ...

『貳』 java 創建file讀取file

/***主要是輸入流的使用,最常用的寫法*@paramfilePath*@return*/publicstaticStringread(StringfilePath){//讀取txt內容為字元串StringBuffertxtContent=newStringBuffer();//每次讀取的byte數byte[]b=newbyte[8*1024];InputStreamin=null;try{//文件輸入流in=newFileInputStream(filePath);while(in.read(b)!=-1){//字元串拼接txtContent.append(newString(b));}//關閉流in.close();}catch(FileNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}returntxtContent.toString();}

『叄』 java文件如何讀取

有幾種方法讀取吧
File
file
=
new
File("d:\\a.txt");//把D盤目錄下的a.txt讀取出來,
InputStream
is
=
new
FileInputStream(file);//把文件以位元組流讀到內存中
第二種是類載入
Demo1.class.getClassLoader().getResourceAsStream("a.txt");//Demo1為當前類名,a.txt在與Demo1.class在同一目錄下。
還有其它的就不說了

『肆』 Java File 讀取文件

應該是Scanner類的操作問題,在使用Scanner類讀文件的時候,要考慮到換行的功能。
我試了下 用下面的方法是可以讀完的。
import java.util.* ;
import java.text.* ;
import java.io.* ;
public class ScannerDemo{
public static void main(String args[]){
File f = new File("D:" + File.separator + "test.txt") ; // 指定操作文件
Scanner scan = null ;
try{
scan = new Scanner(f) ;
}catch(Exception e){}
StringBuffer str = new StringBuffer() ;
while(scan.hasNext()){
str.append(scan.next()).append('\n') ;//取數據
}
System.out.println("文件內容為:" + str) ;
}
};

『伍』 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());
}
}

運行結果如下:

『陸』 java File讀取和復制問題

importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;

publicclassFileIO{
publicstaticvoidmain(String[]args){
Filefile=newFile("D:");
String[]fileList=file.list();

FilenewFile=newFile("D://1.txt");
FileWriterout=null;
try{
out=newFileWriter(newFile);
for(Stringstr:fileList){
out.write(str+" ");
}
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
if(out!=null)
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}

}
}

『柒』 java中如何從文件中讀取數據

1.package txt;
2.
3.import java.io.BufferedReader;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.InputStreamReader;
7.
8./**
9. * 讀取TXE數據
10. */
11.public class ReadTxtUtils {
12. public static void main(String arg[]) {
13. try {
14. String encoding = "GBK"; // 字元編碼(可解決中文亂碼問題 )
15. File file = new File("c:/aa.txt");
16. if (file.isFile() && file.exists()) {
17. InputStreamReader read = new InputStreamReader(
18. new FileInputStream(file), encoding);
19. BufferedReader bufferedReader = new BufferedReader(read);
20. String lineTXT = null;
21. while ((lineTXT = bufferedReader.readLine()) != null) {
22. System.out.println(lineTXT.toString().trim());
23. }
24. read.close();
25. }else{
26. System.out.println("找不到指定的文件!");
27. }
28. } catch (Exception e) {
29. System.out.println("讀取文件內容操作出錯");
30. e.printStackTrace();
31. }
32. }
33.}
java讀取TXT文件中的數據,每一行就是一個數,返回一個數組,代碼?
?
List list=new ArrayList();
BufferedReader br=new BufferReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String str=null;
while((str=br.readLine())!=null)
{
list.add(new Integer(str));

}
Integer[] i=new Integer[list.size()];
list.toArray(i);

TXT文本中如據形如:
123
456
789

讀入二維數組效果為:
temp[0][]={1,2,3};
temp[1][]={4,5,6};
temp[2][]={7,8,9};

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.*;

public class xx{
public static void main(String[]args){
String s;
int[][]save=new int[3][3];
try{
BufferedReader in =new BufferedReader(new FileReader("C:\\txt.txt"));
int i=0;
while((s=in.readLine())!=null){
save[i][0]=Integer.parseInt(s.substring(0,1));
save[i][1]=Integer.parseInt(s.substring(1,2));
save[i][2]=Integer.parseInt(s.substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
System.out.print(save[i][j]);
}
System.out.println();
}
}
}


?
BufferedReader bf=new BufferedReader(new FileReader("Your file"));
String lineContent=null;
int i = 0;
int [][] temp = new int [3][];
while((lineContent=bf.readLine())!=null){
String [] str = lineContent.split("\\d");// 將 lineContent 按數字拆分
for(int j = 0; j < str.length(); j++){
int [i][j] = Integer.parseInt(str[j]);
}
i++;
}

scp|cs|ff|201101
這是d:\\a.txt的數據,與「|」分割取數據出來,保存在變數a;b;c;d里

import java.io.*;

public class Test{
public static void main(String[] args)throws Exception{
String a, b, c, d;
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("d:\\a.txt"));
String s = br.readLine();
while(s != null){
sb.append(s);
s = br.readLine();
}
s = sb.toString();
String[] str = s.split("|");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}

『捌』 java的幾種IO流讀取文件方式

一、超類:


位元組流: InputStream(讀入流) OutputStream(寫出流)


字元流: Reader(字元 讀入流) Writer (字元寫出流)

二、文件操作流


位元組流: FileInputStream ,FileOutputStream


字元流: FileReader, FileWriter(用法與位元組流基本相同,不寫)

//1.指定要讀 的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileInputStream fis =new FileInputStream(file);


//3.定義結束標志,可用位元組數組讀取


int i =0 ;


while((i = fis.read())!=-1){


//i 就是從文件中讀取的位元組,讀完後返回-1


}


//4.關閉流


fis.close();


//5.處理異常

//1.指定要寫到的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileOutputStream fos =new FileOutputStream(file);


//3.定義結束標志


fos.write(要寫出的位元組或者位元組數組);


//4.刷新和關閉流


fos.flush();


fos.close();


//5.處理異常

三、緩沖流:


位元組緩沖流: BufferedInputStream,BufferedOutputStream


字元緩沖流:BufferedReader ,BufferedWriter


緩沖流是對流的操作的功能的加強,提高了數據的讀寫效率。既然緩沖流是對流的功能和讀寫效率的加強和提高,所以在創建緩沖流的對象時應該要傳入要加強的流對象。

//1.指定要讀 的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileInputStream fis =new FileInputStream(file);


//3.創建緩沖流對象加強fis功能


BufferedInputStream bis =new BufferedInputStream(fis);


//4.定義結束標志,可用位元組數組讀取


int i =0 ;


while((i = bis.read())!=-1){


//i 就是從文件中讀取的位元組,讀完後返回-1


}


//5.關閉流


bis.close();


//6.處理異常

//1.指定要寫到的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileOutputStream fos =new FileOutputStream(file);


//3.創建緩沖流對象加強fos功能


BufferedOutputStream bos=new BufferedOutputStream(fos);


//4.向流中寫入數據


bos.write(要寫出的位元組或者位元組數組);


//5.刷新和關閉流


bos.flush();


bos.close();


//6.處理異常

四、對象流


ObjectInputStream ,ObjectOutputStream


不同於以上兩種類型的流這里只能用位元組對對象進行操作原因可以看上篇的編碼表比照原理

ObjectOutputStream對象的序列化:


將java程序中的對象寫到本地磁碟里用ObjectOutputStream


eg:將Person類的對象序列化到磁碟

  1. 創建Person類


    注1:此類要實現Serializable介面,此介面為標志性介面


    注2:此類要有無參的構造函數


    注3:一旦序列化此類不能再修改


    class Person implements Serializable{


    public Person(){}


    }


    2.創建對象流對象


    註:要增強功能可以將傳入文件緩沖流


    ObjectOutputStream oos =new ObjectOutputStream(


    new FileOutputStream(new File("文件路徑")));


    3.寫入對象 ,一般會將對象用集合存儲起來然後直接將集合寫入文件


    List<Person> list =new ArrayList<>();


    list.add(new Person());


    ...(可以添加多個)


    oos.writeObject(list);


    4.關閉流,處理異常


    oos.flush();


    oos.close();

五、轉換流:

這類流是用於將字元轉換為位元組輸入輸出,用於操作字元文件,屬於字元流的子類,所以後綴為reader,writer;前綴inputstream,outputstream;

注 :要傳入位元組流作為參賽


InputStreamReader: 字元轉換輸出流


OutputStreamWriter:字元轉換輸入流

//1.獲取鍵盤輸入的位元組流對象

inInputStream in =Stream.in;

/*2.用轉換流將位元組流對象轉換為字元流對象,方便調用字元緩沖流的readeLine()方法*/


InputStreamReader isr =new InputStreamReader(in);


/*5.創建字元轉換輸出流對象osw,方便把輸入的字元流轉換為位元組輸出到本地文件。*/


OutputStreamWriter osw =new OutputStreamWriter(new
FileOutputStream(new File("文件名")));



/*3.現在isr是字元流,可以作為參數傳入字元緩沖流中*/


BufferedReader br =new BufferedReader(isr);

/*4.可以調用字元緩沖流br的readLine()方法度一行輸入文本*/


String line =null;


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


osw.write(line);//osw是字元流對象,可以直接操作字元串

}



註:InputStreamReader isr =new InputStreamReader(new "各種類型的位元組輸入流都行即是:後綴為InputStream就行");


OutputStreamWriter osw =new OutputStreamWriter(new
"後綴為OutputStream就行");

六、區別記憶


1.對象流是可以讀寫幾乎所有類型的只要是對象就行,而位元組字元流,只能讀寫單個位元組字元或者位元組字元數組,以上沒有讀寫位元組字元數組的;注意對象流只有位元組流!


2.字元和位元組循環讀入的結束條件int i=0; (i =fis.read())!=-1
用字元數組復制文件(fr 讀入流 ,fw寫出流),位元組流也是相同的用法

int i = 0; char[] c = new char[1024];


while((i = fr.reade()) !=-1)){


fw.write(c,0,i);


}

123456

3.對象流裡面套緩沖流的情景:


new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(「文件路徑」))));

4.記憶流及其功能的方法:


前綴表示功能,後綴表示流的類型;


比如說FileInputStream 前綴:File,表示操作的磁碟,後綴:intputstream,表示是位元組輸入流。


同理 FileReader:表示操作文件的字元流


ObjectInputStream :操作對象的位元組輸入流

5.拓展:獲取鍵盤輸入的字元的緩沖流的寫法:


new BufferedReader(new InputStreamReader(System.in)));


將位元組以字元形式輸出到控制台的字元緩沖流的寫法:


new BufferedWriter( new OutputStreamWriter(System.out))

『玖』 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);
}}

『拾』 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);
}
}

熱點內容
分布式緩存部署步驟 發布:2025-05-14 13:24:51 瀏覽:610
php獲取上一月 發布:2025-05-14 13:22:52 瀏覽:89
購買雲伺服器並搭建自己網站 發布:2025-05-14 13:20:31 瀏覽:688
sqlserver建立視圖 發布:2025-05-14 13:11:56 瀏覽:484
搭建httpsgit伺服器搭建 發布:2025-05-14 13:09:47 瀏覽:255
新電腦拿回來我該怎麼配置 發布:2025-05-14 13:09:45 瀏覽:240
視頻伺服器新建ftp用戶 發布:2025-05-14 13:03:09 瀏覽:225
php花生 發布:2025-05-14 12:54:30 瀏覽:550
java人才 發布:2025-05-14 12:29:10 瀏覽:649
如何打開軟密碼 發布:2025-05-14 12:28:55 瀏覽:427