本文目錄一覽:
java 文件讀寫流
首先你要知道java的io流主要分兩種,一種是字符流,另一種位元組流,還有一種過濾流,這個不常用,暫且可以忽略。
等你這些都掌握了,推薦你用nio包中的管道流。
流的套用可以提升讀寫效率(這種方式只能是同類流的套用,比如位元組流套用位元組流),還有一種是字符流與位元組流互相轉換,轉換通過一種叫做「橋轉換」的類,比如OutputStreamWriter類。
下面舉個最基礎的位元組流例子:
public void copyFile(String file, String bak) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
byte[] bytes = new byte[1024];
bis = new BufferedInputStream(new FileInputStream(file));//BufferedInputStream會構造一個背部緩衝區數組,將FileInputStream中的數據存放在緩衝區中,提升了讀取的性能
bos = new BufferedOutputStream(new FileOutputStream(bak));//同理
int length = bis.read(bytes);
while (length != -1) {
System.out.println(“length: ” + length);
bos.write(bytes, 0, length);
length = bis.read(bytes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
字符流的用法:
FileReader fr = new FileReader(“D:\\test.txt”);
BufferedReader br = new BufferedReader(fr);
或者PrintWriter pw = new PrintWriter(new FileWriter(“D:\\test.txt”));
…
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緩衝流讀寫數據
— 下面都是以位元組流方式操作 —
//讀數據:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(“xx.xx”));
byte[] b = new byte[1024];
int len = 0;
while((len=bis.read(b))!-1){
//這樣就讀取並輸出了,如果是別的文件的話亂碼,因為二進制文件
System.out.println(new String(b,0,len));
}
bis.close();//關閉流,節省資源
//寫數據:
BufferedOutputStream bos = new BufferedOutputStream(new FileOuputStream(“xx.xx”));
//使用緩衝區寫二進制位元組數據
bos.write(“xxxxx”.getBytes());
bos.close();//關閉流,節省資源
如果字符流的話就是:
BufferedReader //讀取
BufferedWriter //寫入
Java中對文件進行讀寫操作的基本類是什麼?
Java.io包中包括許多類提供許多有關文件的各個方面操作。
1 輸入輸出抽象基類InputStream/OutputStream ,實現文件內容操作的基本功能函數read()、 write()、close()、skip()等;一般都是創建出其派生類對象(完成指定的特殊功能)來實現文件讀寫。在文件讀寫的編程過程中主要應該注意異常處理的技術。
2 FileInputStream/FileOutputStream:
用於本地文件讀寫(二進制格式讀寫並且是順序讀寫,讀和寫要分別創建出不同的文件流對象);
本地文件讀寫編程的基本過程為:
① 生成文件流對象(對文件讀操作時應該為FileInputStream類,而文件寫應該為FileOutputStream類);
② 調用FileInputStream或FileOutputStream類中的功能函數如read()、write(int b)等)讀寫文件內容;
③ 關閉文件(close())。
3 PipedInputStream/PipedOutputStream:
用於管道輸入輸出(將一個程序或一個線程的輸出結果直接連接到另一個程序或一個線程的輸入端口,實現兩者數據直接傳送。操作時需要連結);
4管道的連接:
方法之一是通過構造函數直接將某一個程序的輸出作為另一個程序的輸入,在定義對象時指明目標管道對象
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream(pInput);
方法之二是利用雙方類中的任一個成員函數 connect()相連接
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream();
pinput.connect(pOutput);
5 管道的輸入與輸出:
輸出管道對象調用write()成員函數輸出數據(即向管道的輸入端發送數據);而輸入管道對象調用read()成員函數可以讀起數據(即從輸出管道中獲得數據)。這主要是藉助系統所提供的緩衝機制來實現的。
6隨機文件讀寫:
RandomAccessFile類(它直接繼承於Object類而非InputStream/OutputStream類),從而可以實現讀寫文件中任何位置中的數據(只需要改變文件的讀寫位置的指針)。
隨機文件讀寫編程的基本過程為:
① 生成流對象並且指明讀寫類型;
② 移動讀寫位置;
③ 讀寫文件內容;
④ 關閉文件。
七里河團隊答疑助人,希望我的回答對你有所幫助
怎樣用Java讀寫二進制文件
import java.util.*;
import java.io.*;
class SmallFile {
static final int HEADLEN = 24; //頭總長度
byte[] fileName = new byte[16]; //列表文件名1: 長度128 想把它讀到char[]里 它的編碼方式不是Unicode。在不確定編碼方式的時候,最好直接用byte[]來存放
int offset; //列表文件地址1: 長度32 想把它讀到int里
int length = -1; //列表文件長度1: 長度32 想把它讀到int里
byte[] content;
public SmallFile() {
}
public SmallFile(byte[] fn, byte[] content) {
Arrays.fill(fileName, (byte) 0);
if (fn != null) {
if (fn.length = 16) {
System.arraycopy(fn, 0, fileName, 0, fn.length);
}
else {
System.arraycopy(fn, 0, fileName, 0, 16);
}
}
this.content = content;
if (content != null) {
this.length = content.length;
}
else {
this.length = -1;
}
}
}
public class ReadBinary {
static final int HEADLEN = 8; //頭總長度
private String filename;
private byte[] filehead = new byte[4]; //文件頭: 長度32 想把它讀到char[]里 它的編碼方式不是Unicode
private int filecount = -1; //列表長度: 長度32 想把它讀到int里 假設他是3 就會有3個列表文件名
private ListSmallFile files = null;
public void setFilehead(byte[] fh) {
if (fh == null)
return;
Arrays.fill(filehead, (byte) 0);
if (fh.length = 4) {
System.arraycopy(fh, 0, filehead, 0, fh.length);
}
else {
System.arraycopy(fh, 0, filehead, 0, 4);
}
}
public ReadBinary(String filename) {
try {
readFromFile(filename);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println(“在載入數據文件時失敗,因此視同為新建一個數據文件!”);
this.filename = filename;
Arrays.fill(filehead, (byte) 0);
filecount = 0;
files = new ArrayListSmallFile ();
}
}
public void readFromFile(String filename) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
filename));
this.filename = filename;
DataInputStream in = new DataInputStream(bin);
in.read(filehead); //文件頭: 長度32 想把它讀到char[]里 它的編碼方式不是Unicode
filecount = in.readInt(); //列表長度: 長度32 想把它讀到int里 假設他是3 就會有3個列表文件名
if (files == null) {
files = new ArrayListSmallFile ();
}
else {
files.clear();
}
for (int i = 0; i filecount; i++) {
SmallFile file = new SmallFile();
in.read(file.fileName);
file.offset = in.readInt(); //列表文件地址1: 長度32 想把它讀到int里
file.length = in.readInt(); //列表文件長度1: 長度32 想把它讀到int里
files.add(file);
}
}
public void writeToFile() throws Exception {
String temp = filename + “.tmp”; //臨時文件
boolean exists = false;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filename, “r”); //文件存在則從文件讀入
exists = true;
}
catch (Exception ex) {
System.out.println(“文件不存在,因此啟用內存寫入模式”);
}
if (filecount != files.size()) {
throw new Exception(“怪事,居然不相同??”);
}
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new
FileOutputStream(temp)));
//1、寫總文件頭
out.write(filehead);
out.writeInt(filecount);
//2、寫列表頭
int sumlength = 0;
for (int i = 0; i files.size(); i++) {
SmallFile file = files.get(i);
out.write(file.fileName);
if (file.length 0) {
throw new Exception(“怪事,文件長度怎麼可能小於0?”);
}
else {
out.writeInt(ReadBinary.HEADLEN + SmallFile.HEADLEN * filecount +
sumlength);
sumlength += file.length;
out.writeInt(file.length);
}
}
//3、寫文件內容
for (int i = 0; i files.size(); i++) {
SmallFile file = files.get(i);
if (file.content != null (file.length == file.content.length)) {
out.write(file.content);
}
else if (exists) {
raf.seek(file.offset);
byte[] b = new byte[file.length];
raf.read(b);
System.out.println(“b:” + new String(b));
out.write(b);
}
else {
throw new Exception(“怪事,又不能從內存讀,又不能從文件讀。這活沒法幹了!”);
}
}
out.close();
if (raf != null) {
raf.close();
raf = null;
}
System.gc();
//把原先的文件刪除
File f = new File(filename);
f.delete();
//再把臨時文件改名到正式文件
File f2 = new File(temp);
f2.renameTo(f);
}
public void addFile(SmallFile file) {
if (files != null) {
filecount++;
files.add(file);
}
}
public static void test1(){
ReadBinary rb = new ReadBinary(“f:\\temp\\rb.dat”);
rb.setFilehead(“HEAD1234567890122222222222222222”.getBytes());
SmallFile f = new SmallFile(“第1個文件”.getBytes(), “第1個文件的內容”.getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public static void test2(){
ReadBinary rb = new ReadBinary(“f:\\temp\\rb.dat”);
rb.setFilehead(“HEA”.getBytes());
SmallFile f = new SmallFile(“第2個文件”.getBytes(), “第2個文件的內容”.getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
//test1();
test2();
}
}
Java讀寫文件的幾種方法
java讀取配置文件的幾種方法如下:
方式一:採用ServletContext讀取,讀取配置文件的realpath,然後通過文件流讀取出來。因為是用ServletContext讀取文件路徑,所以配置文件可以放入在web-info的classes目錄中,也可以在應用層級及web-info的目錄中。文件存放位置具體在eclipse工程中的表現是:可以放在src下面,也可放在web-info及webroot下面等。因為是讀取出路徑後,用文件流進行讀取的,所以可以讀取任意的配置文件包括xml和properties。缺點:不能在servlet外面應用讀取配置信息。
方式二:採用ResourceBundle類讀取配置信息,
優點是:可以以完全限定類名的方式加載資源後,直接的讀取出來,且可以在非Web應用中讀取資源文件。缺點:只能加載類classes下面的資源文件且只能讀取.properties文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/180330.html