导航:首页 > 编程语言 > 读取文件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相关的资料

热点内容
工作三年的大专程序员 浏览:726
java毕业设计文献 浏览:140
筹码集中度指标源码 浏览:477
listsortjava 浏览:183
plc闪光电路编程实例 浏览:297
socket编程试题 浏览:203
华为的服务器怎么设置从光驱启动 浏览:867
程序员真的累吗 浏览:325
学信网app为什么刷脸不了 浏览:872
天蝎vs程序员 浏览:992
单片机下载口叫什么 浏览:188
程序员的道 浏览:926
云服务器不实名违法吗 浏览:558
怎样查看文件夹图片是否重复 浏览:995
文件怎么导成pdf文件 浏览:808
打开sql表的命令 浏览:103
安卓手机如何面部支付 浏览:38
天元数学app为什么登录不上去 浏览:824
明日之后为什么有些服务器是四个字 浏览:104
安卓系统l1是什么意思 浏览:26