导航:首页 > 编程语言 > java读取

java读取

发布时间:2022-01-15 06:48:19

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中如何从文件中读取数据

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文件读取

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中读取文件数据

//使用字符流按行读取
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文件读取!

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

public class Test2 {
public static void main(String args[]) {
int x1, x2, x3, x4;
String string1;
try {
BufferedReader br;
br = new BufferedReader(new FileReader("E:\\bj.bat"));
String lineInfo, lineWords[];
lineInfo = br.readLine();
lineWords = lineInfo.split(" ");
x1 = Integer.parseInt(lineWords[0]);
x2 = Integer.parseInt(lineWords[1]);
x3 = Integer.parseInt(lineWords[2]);
x4 = Integer.parseInt(lineWords[3]);
string1 = lineWords[4];
System.out.println("x1="+x1+",x2="+x2+",x3="+x3+",x4="+x4+",string1="+string1);
} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();}
}
}

❻ 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文件如何读取

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中读入和输出文本文件

/**
*测试3:从文本文件中读取数据
*/
staticvoidtestExample03(){
//1、在内存中打开要读取文件的字符流对象
try{
Readerreader=newFileReader("e:/ReadMe.log");
//2、从字符流中读取数据
//一次读取一个字符(麻烦)
/*intnum=reader.read();
System.out.println((char)num);
num=reader.read();
System.out.println((char)num);*/
//一次读取一个数组(必须确定数组的长度)
/*char[]cbuf=newchar[10];
reader.read(cbuf);
System.out.println(newString(cbuf));*/
//循环读取,一次就读一个
intch=reader.read();
StringBufferbuffer=newStringBuffer();
while(ch!=-1){//读取成功
buffer.append((char)ch);
ch=reader.read();
}
System.out.println(buffer.toString());
//3、关闭流
reader.close();
}catch(FileNotFoundExceptione){
System.out.println("要读取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件读取错误:"+e.getMessage());
}
}
/**
*测试4:向文本文件中写入数据
*/
staticvoidtestExample04(){
System.out.println("请输入内容:");
Stringtext=input.next();
try{
//1、打开流
Writerw=newFileWriter("e:/测试.txt",true);
//2、写入内容
w.write(text);
//3、关闭流
w.close();
}catch(IOExceptione){
System.out.println("文件写入错误:"+e.getMessage());
}
}
/**
*测试5:使用效率高的字符流读写数据
*/
staticvoidtestExample05(){
try{
//1、创建流对象
Readerreader=newFileReader("e:/ReadMe.log");
//构建高效流对象
BufferedReaderbuffReader=newBufferedReader(reader);

//2、读取一行字符串
Stringline=buffReader.readLine();
StringBufferbuffer=newStringBuffer();
while(line!=null){
buffer.append(line+" ");
line=buffReader.readLine();
}
System.out.println(buffer.toString());;
//3、关闭流
buffReader.close();
reader.close();

Writerw=newFileWriter("e:/NewReadMe.txt");
BufferedWriterbuffWriter=newBufferedWriter(w);

buffWriter.write(buffer.toString());

buffWriter.close();
w.close();
System.out.println("写入成功!");

}catch(FileNotFoundExceptione){
System.out.println("要读取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件读取错误:"+e.getMessage());
}
}

❿ Java读取文件的几种方法

方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
方式三:采用ClassLoader方式进行读取配置信息
优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
缺点:只能加载类classes下面的资源文件。
方法4 getResouceAsStream
XmlParserHandler.class.getResourceAsStream 与classloader不同

阅读全文

与java读取相关的资料

热点内容
单片机进制字母对应表 浏览:526
向某人下命令 浏览:625
编程中删除数组中的数 浏览:84
aes对称加密反编译 浏览:548
java编译成exe 浏览:188
gps处理算法 浏览:594
什么app可以和对象存钱 浏览:144
java字符串表达式计算 浏览:328
javacmd环境变量 浏览:49
电视上面找不到全民歌app怎么办 浏览:154
单片机中psw0 浏览:992
优酷视频加密么 浏览:761
本地连接dos命令 浏览:204
云服务器怎么上传金币房卡游戏 浏览:69
Python快递管理可视化 浏览:417
java正则验证数字 浏览:828
猴子网游安卓扫码怎么登录 浏览:355
7天工作总结简短程序员 浏览:60
手机号交易网站源码 浏览:687
计算机算法怎么学 浏览:401