當前位置:首頁 » 編程語言 » java文件讀寫

java文件讀寫

發布時間: 2022-01-13 14:04:02

java文件讀寫

package javaTest;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Test {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
StringBuffer sb = new StringBuffer();
String lineContent = null ;
while( (lineContent = br.readLine()) != null){
StringTokenizer st = new StringTokenizer( lineContent," " );

for( int t=0; st.hasMoreElements() ; t++){
String word = (String) st.nextElement();
sb.append( word );
if( t== 0){
sb.append(" #");
}
if( t==1){
sb.append("*");
}
}
sb.append("\n");
}
PrintWriter pw = new PrintWriter("D:\\test1.txt");
pw.write(sb.toString());
br.close();
pw.close();
}

}

test.txt 這里是放在d盤的根目錄下,內容如下
able adj 有才乾的,能乾的
active adj 主動的,活躍的
adaptable adj 適應性強的
adroit adj 靈巧的,機敏的
運行結果生成在同目錄的 test1.txt中
able #adj*有才乾的,能乾的
active #adj*主動的,活躍的
adaptable #adj*適應性強的
adroit #adj*靈巧的,機敏的

Ⅱ 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文件讀寫

在網上查了很多關於修改文件的方法,不得其要領。自己想了兩個取巧的辦法,來解決對文件的修改。一:讀取一個文件file1(FileReader and BufferedReader),進行操作後寫入file2(FileWriter and BufferedWriter),然後刪除file1,更改file2文件名為file1(Rename()方法)。二:創建字元緩沖流(StringBuffer),讀取文件內容賦給字元緩沖流,再將字元緩沖流中的內容寫入到讀取的文件中。例如: test.txt 這里是放在d盤的根目錄下,內容如下 able adj 有才乾的,能乾的 active adj 主動的,活躍的 adaptable adj 適應性強的 adroit adj 靈巧的,機敏的 運行結果生成在同目錄的 test1.txt中 able #adj*有才乾的,能乾的 active #adj*主動的,活躍的 adaptable #adj*適應性強的 adroit #adj*靈巧的,機敏的 代碼: public class Test { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt")); StringBuffer sb = new StringBuffer(); String lineContent = null ;while( (lineContent = br.readLine()) != null){ String[] sp = lineContent.split(" ");sp[0] = sp[0].concat(" *");sp[1] = sp[1].concat("# ");for(int i=0;i sb.append(sp[i]);}sb.append("\r\n");}FileWriter fw = new FileWriter("D:\\test2.txt"); fw.write(sb.toString()); br.close(); fw.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文件讀寫

實用的模糊(通配符)文件查找程序
1 import java.io.File;
2 import java.util.regex.Matcher;
3 import java.util.regex.Pattern;
4 import java.util.ArrayList;
5
6 /** *//**
7 * <p>Title: FileService </p>
8* <p>Description: 獲取文件 </p>
9* <p>Copyright: Copyright (c) 2007</p>
10* <p>Company: </p>
11* @author not attributable
12* @version 1.0
13*/
14public class FileService {
15 public FileService() {
16 }
17
18 /** *//**
19 * 在本文件夾下查找
20 * @param s String 文件名
21 * @return File[] 找到的文件
22 */
23 public static File[] getFiles(String s)
24 {
25 return getFiles("./",s);
26 }
27
28 /** *//**
29 * 獲取文件
30 * 可以根據正則表達式查找
31 * @param dir String 文件夾名稱
32 * @param s String 查找文件名,可帶*.?進行模糊查詢
33 * @return File[] 找到的文件
34 */
35 public static File[] getFiles(String dir,String s) {
36 //開始的文件夾
37 File file = new File(dir);
38
39 s = s.replace('.', '#');
40 s = s.replaceAll("#", "\\\\.");
41 s = s.replace('*', '#');
42 s = s.replaceAll("#", ".*");
43 s = s.replace('?', '#');
44 s = s.replaceAll("#", ".?");
45 s = "^" + s + "$";
46
47 System.out.println(s);
48 Pattern p = Pattern.compile(s);
49 ArrayList list = filePattern(file, p);
50
51 File[] rtn = new File[list.size()];
52 list.toArray(rtn);
53 return rtn;
54 }
55
56 /** *//**
57 * @param file File 起始文件夾
58 * @param p Pattern 匹配類型
59 * @return ArrayList 其文件夾下的文件夾
60 */
61
62 private static ArrayList filePattern(File file, Pattern p) {
63 if (file == null) {
64 return null;
65 }
66 else if (file.isFile()) {
67 Matcher fMatcher = p.matcher(file.getName());
68 if (fMatcher.matches()) {
69 ArrayList list = new ArrayList();
70 list.add(file);
71 return list;
72 }
73 }
74 else if (file.isDirectory()) {
75 File[] files = file.listFiles();
76 if (files != null && files.length > 0) {
77 ArrayList list = new ArrayList();
78 for (int i = 0; i < files.length; i++) {
79 ArrayList rlist = filePattern(files[i], p);
80 if (rlist != null) {
81 list.addAll(rlist);
82 }
83 }
84 return list;
85 }
86 }
87 return null;
88 }
89
90 /** *//**
91 * 測試
92 * @param args String[]
93 */
94 public static void main(String[] args) {
95 }
96}

Ⅵ java 如何讀寫文件

這個問題問的太泛泛了,讀寫文件,首先了解什麼是輸入流和輸出流,什麼是位元組流,什麼是字元流。然後創建流對象,調用其方法read or write File

Ⅶ 如何在java中讀寫文件

FileOutputStream 的一個構造方法中有兩個參數,第一個為文件路徑,第二個參數為boolen值. 列如:
FileOutputStream fos=FileOutputStream("c:\\test.txt",true);
當第二個參數設為true時,則在文件末尾追加數據;
當第二個參數設為false時,則重寫文件;

注意:第二個參數可以不寫,預設值為false

Ⅷ Java讀寫文件的幾種方法

java讀取配置文件的幾種方法如下:
方式一:採用ServletContext讀取,讀取配置文件的realpath,然後通過文件流讀取出來。因為是用ServletContext讀取文件路徑,所以配置文件可以放入在web-info的classes目錄中,也可以在應用層級及web-info的目錄中。文件存放位置具體在eclipse工程中的表現是:可以放在src下面,也可放在web-info及webroot下面等。因為是讀取出路徑後,用文件流進行讀取的,所以可以讀取任意的配置文件包括xml和properties。缺點:不能在servlet外面應用讀取配置信息。
方式二:採用ResourceBundle類讀取配置信息,
優點是:可以以完全限定類名的方式載入資源後,直接的讀取出來,且可以在非Web應用中讀取資源文件。缺點:只能載入類classes下面的資源文件且只能讀取.properties文件。

Ⅸ java怎樣實現讀寫TXT文件

主要有用到java原生態的Io類,沒有第三個包。直接上代碼:

importjava.io.*;

publicclasswrite{
publicstaticvoidmain(String[]args){
write("E://123.txt","hello");
}

publicstaticvoidwrite(Stringpath,Stringcontent){
try{
Filef=newFile(path);

if(f.exists()){
System.out.println("文件存在");
}else{
System.out.println("文件不存在,正在創建...");
if(f.createNewFile()){
System.out.println("文件創建成功!");
}else{
System.out.println("文件創建失敗!");
}
}
BufferedWriteroutput=newBufferedWriter(newFileWriter(f));
output.write(content);
output.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}

Ⅹ 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. }

熱點內容
伺服器換位置了ip地址怎麼換 發布:2024-09-19 09:33:50 瀏覽:798
javarest 發布:2024-09-19 09:28:43 瀏覽:753
密碼子的原料是什麼 發布:2024-09-19 09:11:42 瀏覽:348
半夜編程 發布:2024-09-19 09:11:36 瀏覽:104
海康威視存儲卡質量如何 發布:2024-09-19 08:55:35 瀏覽:941
python3默認安裝路徑 發布:2024-09-19 08:50:22 瀏覽:517
環衛視頻拍攝腳本 發布:2024-09-19 08:35:44 瀏覽:419
sqlserveronlinux 發布:2024-09-19 08:16:54 瀏覽:257
編程常數 發布:2024-09-19 08:06:36 瀏覽:953
甘肅高性能邊緣計算伺服器雲空間 發布:2024-09-19 08:06:26 瀏覽:163