導航:首頁 > 編程語言 > 讀取文件java

讀取文件java

發布時間:2022-01-20 03:23:15

『壹』 java讀取整個文本文件

可以通過BufferedReader 流的形式進行流緩存,之後通過readLine方法獲取到緩存的內容。
BufferedReader bre = null;
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此時獲取到的bre就是整個文件的緩存流
while ((str = bre.readLine())!= null) // 判斷最後一行不存在,為空結束循環
{
System.out.println(str);//原樣輸出讀到的內容
};
備註: 流用完之後必須close掉,如上面的就應該是:bre.close(),否則bre流會一直存在,直到程序運行結束。

『貳』 java實時讀取文件

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.Timer;
importjava.util.TimerTask;

publicclassDemo{

privatestaticFilefile;//文件
privatestaticlonglastModified;//文件最後修改時間

privatestaticStringcontent;

publicstaticvoidmain(String[]args){

StringfilePath="D:/test.txt";

try{
file=newFile(filePath);
readFile(file);

lastModified=file.lastModified();
//定義定時器,監控文件的修改
Timertimer=newTimer();
timer.schele(newTimerTask(){
@Override
publicvoidrun(){
longmodifiedTime=file.lastModified();
if(modifiedTime!=lastModified){//文件內容有修改時再重新讀取
System.out.println("文件內容修改,重新載入。。。");
readFile(file);
lastModified=modifiedTime;
}
}
},0,10000);//延遲0秒執行,每10秒執行一次
}catch(Exceptione){
e.printStackTrace();
}
}

staticvoidreadFile(Filefile){
try{
BufferedReaderreader=newBufferedReader(newInputStreamReader(newFileInputStream(file),"UTF-8"));
StringBufferbuffer=newStringBuffer();
Stringtemp;
while((temp=reader.readLine())!=null){
buffer.append(temp);
}
reader.close();

content=buffer.toString();
System.out.println("文件內容:"+content);
}catch(FileNotFoundExceptione){
System.out.println("文件不存在");
}catch(IOExceptione){
System.err.println("讀取文件出錯");
}
}
}

『叄』 java讀取文件操作

關於FileInputStream你的理解是對的,讀取操作是順序向前,讀過的不會再讀。
不過第二個參數0你可能是誤會了。它的作用不是指fis里的位置,而是指buffer里的偏移量。
在read中,0是指從buffer[0]開始保存數據;wirte中是指寫出的數據是從buffer[0]開始。
Java Doc里的解釋是這樣的:
int java.io.FileInputStream.read(byte[] b, int off, int len) throws IOException
b the buffer into which the data is read.
off the start offset in the destination array b
len the maximum number of bytes read.

『肆』 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中怎樣從一個文件中讀取文件信息

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中讀取文件數據

//使用字元流按行讀取
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());

『柒』 java中文件讀取的時候,要被讀取的文件應該放哪

被讀取的文件可以放在硬碟的任意位置。 只要你新建文件IO流對象的時候把文件的物理路徑寫對就行了。代碼例子如下:

importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;

/**
*fileIO流讀取並輸出文件
*@authoryoung
*
*/
publicclassFileIO{
publicstaticvoidmain(String[]args)throwsIOException{

FileInputStreamfis=newFileInputStream("F:/workspace/one/src/filecode/FileIO.java");//要讀的文件路徑

InputStreamReaderisr=newInputStreamReader(fis);//字元流

BufferedReaderbr=newBufferedReader(isr);//緩沖
Stringline=null;

while((line=br.readLine())!=null){//字元不等於空
System.out.println(line);//一行一行地輸出
}
br.close();//關閉文件
}
}

『捌』 java文件讀取

String
path
=
System.getProperty("user.dir")//得到當前工作路徑
File
fileData;
FileReader
fr;
BufferedReader
br;
fileData=new
File(path,file);
//file如1.txt文件名.需要在path即工作路徑下.path為工作路徑
也可以改為其他
try
{
fr=new
FileReader(fileData);
br=new
BufferedReader(fr);
}
catch
(Exception
ex)
{
ex.printStackTrace();
}
String
result
=
br.readLine();
然後將result中數據(如果為數字則可將字元取出轉化為數字再排序)操作

『玖』 java文件如何讀取

java讀取文件方法大全
一、多種方式讀文件內容。

1、按位元組讀取文件內容
2、按字元讀取文件內容
3、按行讀取文件內容
4、隨機讀取文件內容
Java代碼
1. import java.io.BufferedReader;
2. import java.io.File;
3. import java.io.FileInputStream;
4. import java.io.FileReader;
5. import java.io.IOException;
6. import java.io.InputStream;
7. import java.io.InputStreamReader;
8. import java.io.RandomAccessFile;
9. import java.io.Reader;
10.
11. public class ReadFromFile {
12. /**
13. * 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
14. *
15. * @param fileName
16. * 文件的名
17. */
18. public static void readFileByBytes(String fileName) {
19. File file = new File(fileName);
20. InputStream in = null;
21. try {
22. System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
23. // 一次讀一個位元組
24. in = new FileInputStream(file);
25. int tempbyte;
26. while ((tempbyte = in.read()) != -1) {
27. System.out.write(tempbyte);
28. }
29. in.close();
30. } catch (IOException e) {
31. e.printStackTrace();
32. return;
33. }
34. try {
35. System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
36. // 一次讀多個位元組
37. byte[] tempbytes = new byte[100];
38. int byteread = 0;
39. in = new FileInputStream(fileName);
40. ReadFromFile.showAvailableBytes(in);
41. // 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
42. while ((byteread = in.read(tempbytes)) != -1) {
43. System.out.write(tempbytes, 0, byteread);
44. }
45. } catch (Exception e1) {
46. e1.printStackTrace();
47. } finally {
48. if (in != null) {
49. try {
50. in.close();
51. } catch (IOException e1) {
52. }
53. }
54. }
55. }
56.
57. /**
58. * 以字元為單位讀取文件,常用於讀文本,數字等類型的文件
59. *
60. * @param fileName
61. * 文件名
62. */
63. public static void readFileByChars(String fileName) {
64. File file = new File(fileName);
65. Reader reader = null;
66. try {
67. System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
68. // 一次讀一個字元
69. reader = new InputStreamReader(new FileInputStream(file));
70. int tempchar;
71. while ((tempchar = reader.read()) != -1) {
72. // 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
73. // 但如果這兩個字元分開顯示時,會換兩次行。
74. // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
75. if (((char) tempchar) != '\r') {
76. System.out.print((char) tempchar);
77. }
78. }
79. reader.close();
80. } catch (Exception e) {
81. e.printStackTrace();
82. }
83. try {
84. System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
85. // 一次讀多個字元
86. char[] tempchars = new char[30];
87. int charread = 0;
88. reader = new InputStreamReader(new FileInputStream(fileName));
89. // 讀入多個字元到字元數組中,charread為一次讀取字元數
90. while ((charread = reader.read(tempchars)) != -1) {
91. // 同樣屏蔽掉\r不顯示
92. if ((charread == tempchars.length)
93. && (tempchars[tempchars.length - 1] != '\r')) {
94. System.out.print(tempchars);
95. } else {
96. for (int i = 0; i < charread; i++) {
97. if (tempchars[i] == '\r') {
98. continue;
99. } else {
100. System.out.print(tempchars[i]);
101. }
102. }
103. }
104. }
105.
106. } catch (Exception e1) {
107. e1.printStackTrace();
108. } finally {
109. if (reader != null) {
110. try {
111. reader.close();
112. } catch (IOException e1) {
113. }
114. }
115. }
116. }
117.
118. /**
119. * 以行為單位讀取文件,常用於讀面向行的格式化文件
120. *
121. * @param fileName
122. * 文件名
123. */
124. public static void readFileByLines(String fileName) {
125. File file = new File(fileName);
126. BufferedReader reader = null;
127. try {
128. System.out.println("以行為單位讀取文件內容,一次讀一整行:");
129. reader = new BufferedReader(new FileReader(file));
130. String tempString = null;
131. int line = 1;
132. // 一次讀入一行,直到讀入null為文件結束
133. while ((tempString = reader.readLine()) != null) {
134. // 顯示行號
135. System.out.println("line " + line + ": " + tempString);
136. line++;
137. }
138. reader.close();
139. } catch (IOException e) {
140. e.printStackTrace();
141. } finally {
142. if (reader != null) {
143. try {
144. reader.close();
145. } catch (IOException e1) {
146. }
147. }
148. }
149. }
150.
151. /**
152. * 隨機讀取文件內容
153. *
154. * @param fileName
155. * 文件名
156. */
157. public static void readFileByRandomAccess(String fileName) {
158. RandomAccessFile randomFile = null;
159. try {
160. System.out.println("隨機讀取一段文件內容:");
161. // 打開一個隨機訪問文件流,按只讀方式
162. randomFile = new RandomAccessFile(fileName, "r");
163. // 文件長度,位元組數
164. long fileLength = randomFile.length();
165. // 讀文件的起始位置
166. int beginIndex = (fileLength > 4) ? 4 : 0;
167. // 將讀文件的開始位置移到beginIndex位置。
168. randomFile.seek(beginIndex);
169. byte[] bytes = new byte[10];
170. int byteread = 0;
171. // 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
172. // 將一次讀取的位元組數賦給byteread
173. while ((byteread = randomFile.read(bytes)) != -1) {
174. System.out.write(bytes, 0, byteread);
175. }
176. } catch (IOException e) {
177. e.printStackTrace();
178. } finally {
179. if (randomFile != null) {
180. try {
181. randomFile.close();
182. } catch (IOException e1) {
183. }
184. }
185. }
186. }
187.
188. /**
189. * 顯示輸入流中還剩的位元組數
190. *
191. * @param in
192. */
193. private static void showAvailableBytes(InputStream in) {
194. try {
195. System.out.println("當前位元組輸入流中的位元組數為:" + in.available());
196. } catch (IOException e) {
197. e.printStackTrace();
198. }
199. }
200.
201. public static void main(String[] args) {
202. String fileName = "C:/temp/newTemp.txt";
203. ReadFromFile.readFileByBytes(fileName);
204. ReadFromFile.readFileByChars(fileName);
205. ReadFromFile.readFileByLines(fileName);
206. ReadFromFile.readFileByRandomAccess(fileName);
207. }
208. }

二、將內容追加到文件尾部
1. import java.io.FileWriter;
2. import java.io.IOException;
3. import java.io.RandomAccessFile;
4.
5. /**
6. * 將內容追加到文件尾部
7. */
8. public class AppendToFile {
9.
10. /**
11. * A方法追加文件:使用RandomAccessFile
12. * @param fileName 文件名
13. * @param content 追加的內容
14. */
15. public static void appendMethodA(String fileName, String content) {
16. try {
17. // 打開一個隨機訪問文件流,按讀寫方式
18. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
19. // 文件長度,位元組數
20. long fileLength = randomFile.length();
21. //將寫文件指針移到文件尾。
22. randomFile.seek(fileLength);
23. randomFile.writeBytes(content);
24. randomFile.close();
25. } catch (IOException e) {
26. e.printStackTrace();
27. }
28. }
29.
30. /**
31. * B方法追加文件:使用FileWriter
32. * @param fileName
33. * @param content
34. */
35. public static void appendMethodB(String fileName, String content) {
36. try {
37. //打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
38. FileWriter writer = new FileWriter(fileName, true);
39. writer.write(content);
40. writer.close();
41. } catch (IOException e) {
42. e.printStackTrace();
43. }
44. }
45.
46. public static void main(String[] args) {
47. String fileName = "C:/temp/newTemp.txt";
48. String content = "new append!";
49. //按方法A追加文件
50. AppendToFile.appendMethodA(fileName, content);
51. AppendToFile.appendMethodA(fileName, "append end. \n");
52. //顯示文件內容
53. ReadFromFile.readFileByLines(fileName);
54. //按方法B追加文件
55. AppendToFile.appendMethodB(fileName, content);
56. AppendToFile.appendMethodB(fileName, "append end. \n");
57. //顯示文件內容
58. ReadFromFile.readFileByLines(fileName);
59. }
60. }

『拾』 java讀取txt文件

importjava.io.File;

publicclassTest{
publicstaticvoidmain(String[]args){
try{
Filefile=newFile("info.txt");
newRead().readFile(file);
}catch(Exceptione){
e.printStackTrace();
}
}
}
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.util.ArrayList;

publicclassRead{
publicvoidreadFile(Filefile){
ArrayList<String>arrayList=newArrayList<>();
try{
BufferedReaderbufferedReader=newBufferedReader(newFileReader(file));
inti=1;
Stringline=null;
Stringperson="";
while((line=bufferedReader.readLine())!=null){
String[]strings=line.split("\s+");
for(Strings:strings){
if(i!=4){
person+=s+",";
}
else{
person+=s;
arrayList.add(person);
person="";
i=0;
}
i++;
}
}
System.out.println("{");
for(i=0;i<arrayList.size();i++){
Strings=arrayList.get(i);
if(i!=arrayList.size()-1)
System.out.print("["+s+"];");
else
System.out.print("["+s+"]");
}
System.out.println("}");
}catch(Exceptione){
e.printStackTrace();
}
}
}

閱讀全文

與讀取文件java相關的資料

熱點內容
listsortjava 瀏覽:180
plc閃光電路編程實例 瀏覽:297
socket編程試題 瀏覽:201
華為的伺服器怎麼設置從光碟機啟動 瀏覽:867
程序員真的累嗎 瀏覽:323
學信網app為什麼刷臉不了 瀏覽:871
天蠍vs程序員 瀏覽:991
單片機下載口叫什麼 瀏覽:186
程序員的道 瀏覽:924
雲伺服器不實名違法嗎 瀏覽:556
怎樣查看文件夾圖片是否重復 瀏覽:993
文件怎麼導成pdf文件 瀏覽:806
打開sql表的命令 瀏覽:101
安卓手機如何面部支付 瀏覽:37
天元數學app為什麼登錄不上去 瀏覽:822
明日之後為什麼有些伺服器是四個字 瀏覽:103
安卓系統l1是什麼意思 瀏覽:25
伺服器一直崩應該用什麼指令 瀏覽:924
cm202貼片機編程 瀏覽:729
php構造函數帶參數 瀏覽:179