『壹』 java 怎麼讀寫文件
IO中的 FileInputStream 和 FileOutputStream 屬於位元組輸入流和輸出流,前者是用於讀入文件,後者用於寫出文件
FileWriter 和 FileReader 屬於字元流 ,前者用於讀入文件,後者用於寫出文件
File file = new File("E:\\abc.txt");
try {
FileInputStream fis = new FileInputStream(file);
//此時文件已經讀入
FileOutputStream fos = new FileOutputStream("D:\\a.txt");
//此時是寫出文件
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
『貳』 java讀取、修改、寫入txt文件
模擬:先創建一個TXT文件(內容來自控制台);然後讀取文件並在控制台輸出;最後實現對新創建的TXT文件(的數據進行排序後)的復制。分別對應三個函數,調用順序需要注意:創建、讀取、復制。
效果圖如下:綠色部分為控制台輸入的內容(當輸入end時,結束)
packagecom.;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.util.Arrays;
importjava.util.Scanner;
importjava.util.Vector;
publicclassCreateAndReadTxt{
//文件名稱
publicstaticStringfileName=".txt";
publicstaticStringnewFileName=".txt";
//文件路徑
publicfinalstaticStringURL=System.getProperty("user.dir");
//CreateAndReadTxt.class.getResource("/").getPath();
//創建TXT文件
publicstaticvoidcreateTxtFile(StringfName,StringfileContent){
//創建文件
fileName=fName+fileName;
Filefile=newFile(fileName);
//可以更改
file.setWritable(true);
//判斷當前路徑下是否存在同名文件
booleanisExist=file.exists();
if(isExist){
//文件存在,刪除
file.delete();
}
//寫入文件
try{
//文件寫入對象
FileOutputStreamfos=newFileOutputStream(file);
//輸入流寫入----默認字元為GBK
OutputStreamWriterosw=newOutputStreamWriter(fos);
//寫入
osw.write(fileContent);
//寫入完畢後關閉
osw.close();
System.out.println("成功創建文件: "+fileName);
}catch(IOExceptione){
System.out.println("寫入文件失敗: "+e.getMessage());
}
}
//閱讀文件
publicstaticvoidreadFile(StringfileName){
System.out.println("開始讀取文件: "+fileName);
//產生文件對象
Filefile=newFile(fileName);
//
try{
//字元讀取
FileReaderfr=newFileReader(file);
//緩沖處理
BufferedReaderbr=newBufferedReader(fr);
Stringstr="";
while((str=br.readLine())!=null){
System.out.println(str);
}
//關閉
br.close();
fr.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
//文件復制
publicstaticvoidFile(StringfromFileName,StringtoFileName){
//讀取文件
Filefile=newFile(fromFileName);
try{
FileReaderfr=newFileReader(file);
BufferedReaderbr=newBufferedReader(fr);
//定義接收變數
Vector<Double>vec=newVector<Double>();
Strings="";
while(null!=(s=br.readLine())){
vec.add(Double.parseDouble(s));
}
br.close();
fr.close();
//保存到數組並進行排序
Doubledou[]=newDouble[vec.size()];
vec.toArray(dou);
Arrays.sort(dou);
System.out.println("========復制文件=========");
//寫入新文件
newFileName="副本"+newFileName;
FilenewFile=newFile(toFileName);
FileOutputStreamfos=newFileOutputStream(newFile,true);
OutputStreamWriterosm=newOutputStreamWriter(fos);
for(Doubled:dou){
osm.write(d.doubleValue()+"
");
}
osm.close();
fos.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
publicstaticvoidmain(String[]args){
/**
*構造數據
*/
Scannerscan=newScanner(System.in);
StringBuildersb=newStringBuilder();
Strings="";
while(!("end".equals(s=scan.next()))){//當輸入end時,結束
sb.append(s);
sb.append("
");
}
scan.close();
/**
*使用數據
*/
CreateAndReadTxt.createTxtFile("creat",sb.toString());
CreateAndReadTxt.readFile(fileName);
System.out.println(fileName);
CreateAndReadTxt.File(fileName,newFileName);
CreateAndReadTxt.readFile(newFileName);
}
}
『叄』 在Java 7中如何對文件進行操作
1.創建文件
2.刪除文件
3.復制文件
4.文件移動/改名
這文件是以對Java7里提供的新的Path類很熟悉為前提,如果不熟悉這個類,Path 是文件系統里對位置的一個邏輯概念,例如 c: 和 ../foobar.txt 都是Path。
5.創建和刪除文件
下面的代碼片段展示的是用 Files.createFile(Path target) 方法創建文件的基本用法。
Path target = Paths.get("D:\Backup\MyStuff.txt"); Path file = Files.createFile(target);
很多時候,出於安全的原因,可能希望在創建的文件上設置一下屬性,例如:是否可讀/可寫/寫執行。這些屬性依賴於文件系統的種類,需要使用跟文件系統相應的許可權輔助類來完成這種操作。例如,PosixFilePermission和PosixFilePermissions 為 POSIX 文件系統設計的。下面的是在POSIX文件系統上的文件設置讀寫許可權的用法。
Path target = Paths.get("D:\Backup\MyStuff.txt"); Set<PosixFilePermission> perms= PosixFilePermissions.fromString("rw-rw-rw-"); FileAttribute<Set<PosixFilePermission>> attr= PosixFilePermissions.asFileAttribute(perms); Files.createFile(target, attr);
這個 java.nio.file.attribute 包里提供了很多關於 FilePermission 的類。
警告 當創建一個帶有許可權屬性的文件時,請注意包含這個文件的文件夾是否有許可權的強制約束。例如,會發現,由於這些限制,盡管給創建的文件指定了 rw-rw-rw 許可權,實際創建的結果卻是 rw-r–r– 。
6.刪除文件,使用 Files.delete(Path) 這個方法。
Path target = Paths.get("D:\Backup\MyStuff.txt"); Files.delete(target);
拷貝和移動文件
下面的代碼向展示的是使用 Files.(Path source, Path target) 方法做文件拷貝的基本用法。
Path source = Paths.get("C:\My Documents\Stuff.txt"); Path target = Paths.get("D:\Backup\MyStuff.txt"); Files.(source, target);
經常的,在拷貝文件的過程中可能希望指定一些操作設置。在Java7里,可以通過使用 StandardCopyOption enum 來設置這些屬性。下面看一個例子。
import static java.nio.file.StandardCopyOption.*;Path source = Paths.get("C:\My Documents\Stuff.txt");Path target = Paths.get("D:\Backup\MyStuff.txt");Files.(source, target, REPLACE_EXISTING);
拷貝操作時可以使用的屬性還包括COPY_ATTRIBUTES (保留文件屬性) 和 ATOMIC_MOVE (確保移動事務操作的成功,否則進行回滾)。
移動文件的操作跟拷貝很相似,使用 Files.move(Path source, Path target) 方法。
同樣,也可以指定移動操作的屬性,使用 Files.move(Path source, Path target, CopyOptions...) 方法里的參數來設置。
import static java.nio.file.StandardCopyOption.*; Path source = Paths.get("C:\My Documents\Stuff.txt"); Path target = Paths.get("D:\Backup\MyStuff.txt"); Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
可以看出,新的用於文件操作的 NIO.2 API 非常便於使用。
『肆』 java中關於文件讀寫操作
try{
String s=null;
BufferedReader reader=new BufferedReader(new FileReader("D:\\error.txt"));
FileWriter writer=new FileWriter("D:\\test.txt");
boolean serious=false;
while((s=reader.readLine())!=-1){
if(serious){
writer.write(s);
}
if(s=="serious error") serious=true;
}
}catch(Exception e){}
『伍』 如何在java中讀寫文件
FileOutputStream 的一個構造方法中有兩個參數,第一個為文件路徑,第二個參數為boolen值. 列如:
FileOutputStream fos=FileOutputStream("c:\\test.txt",true);
當第二個參數設為true時,則在文件末尾追加數據;
當第二個參數設為false時,則重寫文件;
注意:第二個參數可以不寫,預設值為false
『陸』 java 中簡述使用流進行讀寫文本文件的步驟
一、Java IO學習基礎之讀寫文本文件
Java的IO操作都是基於流進行操作的,為了提高讀寫效率一般需要進行緩沖。
簡單的示常式序如下:
/**
* 讀出1.txt中的內容,寫入2.txt中
*
*/
import java.io.*;
public class ReadWriteFile{
public static void main(String[] args){
try{
File read = new File("c:\\1.txt");
File write = new File("c:\\2.txt");
BufferedReader br = new BufferedReader(
new FileReader(read));
BufferedWriter bw = new BufferedWriter(
new FileWriter(write));
String temp = null;
temp = br.readLine();
while(temp != null){
//寫文件
bw.write(temp + "\r\n"); //只適用Windows系統
//繼續讀文件
temp = br.readLine();
}
bw.close();
br.close();
}catch(FileNotFoundException e){ //文件未找到
System.out.println (e);
}catch(IOException e){
System.out.println (e);
}
}
}
以上是一個比較簡單的基礎示例。本文上下兩部分都是從網上摘抄,合並在一起,方便下自己以後查找。
二、Java IO學習筆記+代碼
文件對象的生成和文件的創建
/*
* ProcessFileName.java
*
* Created on 2006年8月22日, 下午3:10
*
* 文件對象的生成和文件的創建
*/
package study.iostudy;
import java.io.*;
public class GenerateFile
{
public static void main(String[] args)
{
File dirObject = new File("d:\\mydir");
File fileObject1 = new File("oneFirst.txt");
File fileObject2 = new File("d:\\mydir", "firstFile.txt");
System.out.println(fileObject2);
try
{
dirObject.mkdir();
}catch(SecurityException e)
{
e.printStackTrace();
}
try
{
fileObject2.createNewFile();
fileObject1.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
文件名的處理
/*
* ProcessFileName.java
*
* Created on 2006年8月22日, 下午3:29
*
* 文件名的處理
*/
package study.iostudy;
import java.io.*;
/*
* 文件名的處理
* String getName(); 獲得文件的名稱,不包含文件所在的路徑。
* String getPath(); 獲得文件的路徑。
* String getAbsolutePath(); 獲得文件的絕對路徑。
* String getParent(); 獲得文件的上一級目錄的名稱。
* String renameTo(File newName); 按參數中給定的完整路徑更改當前的文件名。
* int compareTo(File pathName); 按照字典順序比較兩個文件對象的路徑。
* boolean isAbsolute(); 測試文件對象的路徑是不是絕對路徑。
*/
public class ProcesserFileName
{
public static void main(String[] args)
{
File fileObject1 = new File("d:\\mydir\\firstFile.txt");
File fileObject2 = new File("d:\\firstFile.txt");
boolean pathAbsolute = fileObject1.isAbsolute();
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
System.out.println("There are some information of fileObject1's file name:");
System.out.println("fileObject1: " + fileObject1);
System.out.println("fileObject2: " + fileObject2);
System.out.println("file name: " + fileObject1.getName());
System.out.println("file path: " + fileObject1.getPath());
System.out.println("file absolute path: " + fileObject1.getAbsolutePath());
System.out.println("file's parent directory: " + fileObject1.getParent());
System.out.println("file's absoulte path: " + pathAbsolute);
int sameName = fileObject1.compareTo(fileObject2);
System.out.println("fileObject1 compare to fileObject2: " + sameName);
fileObject1.renameTo(fileObject2);
System.out.println("file's new name: " + fileObject1.getName());
}
}
測試和設置文件屬性
/*
* SetterFileAttribute.java
*
* Created on 2006年8月22日, 下午3:51
*
* 測試和設置文件屬性
*/
package study.iostudy;
import java.io.*;
public class SetterFileAttribute
{
/*
* File類中提供的有關文件屬性測試方面的方法有以下幾種:
* boolean exists(); 測試當前文件對象指示的文件是否存在。
* boolean isFile(); 測試當前文件對象是不是文件。
* boolean isDirectory(); 測試當前文件對象是不是目錄。
* boolean canRead(); 測試當前文件對象是否可讀。
* boolean canWrite(); 測試當前文件對象是否可寫。
* boolean setReadOnly(); 將當前文件對象設置為只讀。
* long length(); 獲得當前文件對象的長度。
*/
public static void main(String[] args)
{
File dirObject = new File("d:\\mydir");
File fileObject = new File("d:\\mydir\\firstFile.txt");
try
{
dirObject.mkdir();
fileObject.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
System.out.println("there are some information about property of file object:");
System.out.println("file object : " + fileObject);
System.out.println("file exist? " + fileObject.exists());
System.out.println("Is a file? " + fileObject.isFile());
System.out.println("Is a directory?" + fileObject.isDirectory());
System.out.println("Can read this file? " + fileObject.canRead());
System.out.println("Can write this fie? " + fileObject.canWrite());
long fileLen = fileObject.length();
System.out.println("file length: " +fileLen);
boolean fileRead = fileObject.setReadOnly();
System.out.println(fileRead);
System.out.println("Can read this file? " + fileObject.canRead());
System.out.println("Can write this fie? " + fileObject.canWrite());
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
}
}
文件操作方法
/*
* FileOperation.java
*
* Created on 2006年8月22日, 下午4:25
*
* 文件操作方法
*/
package study.iostudy;
import java.io.*;
/*
* 有關文件操作方面的方法有如下幾種:
* boolean createNewFile(); 根據當前的文件對象創建一個新的文件。
* boolean mkdir(); 根據當前的文件對象生成一目錄,也就是指定路徑下的文件夾。
* boolean mkdirs(); 也是根據當前的文件對象生成一個目錄,
* 不同的地方在於該方法即使創建目錄失敗,
* 也會成功參數中指定的所有父目錄。
* boolean delete(); 刪除當前的文件。
* void deleteOnExit(); 當前Java虛擬機終止時刪除當前的文件。
* String list(); 列出當前目錄下的文件。
*/
public class FileOperation
* 找出一個目錄下所有的文件
package study.iostudy;
import java.io.*;
public class SearchFile
{
public static void main(String[] args)
{
File dirObject = new File("D:\\aa");
Filter1 filterObj1 = new Filter1("HTML");
Filter2 filterObj2 = new Filter2("Applet");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("list HTML files in directory: " + dirObject);
String[] filesObj1 = dirObject.list(filterObj1);
for (int i = 0; i < filesObj1.length; i++)
{
File fileObject = new File(dirObject, filesObj1[i]);
System.out.println(((fileObject.isFile())
? "HTML file: " : "sub directory: ") + fileObject);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String[] filesObj2 = dirObject.list(filterObj2);
for (int i = 0; i < filesObj2.length; i++)
{
File fileObject = new File(dirObject, filesObj2[i]);
System.out.println(((fileObject.isFile())
? "htm file: " : "sub directory: ") + fileObject);
}
}
}
class Filter1 implements FilenameFilter
{
String fileExtent;
Filter1(String extentObj)
{
fileExtent = extentObj;
}
public boolean accept(File dir, String name)
{
return name.endsWith("." + fileExtent);
}
}
class Filter2 implements FilenameFilter
{
String fileName;
Filter2(String fileName)
{
this.fileName = fileName;
字元流處理
* ProcesserCharacterStream.java
* 字元流處理
*
* java.io包中加入了專門用於字元流處理的類,這些類都是Reader和Writer類的子類,
* Reader和Writer是兩個抽象類,只提供了一系列用於字元流處理的介面,不能生成這
* 兩個類的實例。
* java.io包中用於字元流處理的最基本的類是InputStreamReader和OutputStreamWriter,
* 用來在位元組流和字元流之間作為中介。
*
* 下面是InputStreamReader類和OutputStreamWriter類的常用方法:
*
* public InputStreamReader(InputStream in)
* 根據當前平台預設的編碼規范,基於位元組流in生成一個輸入字元流。
* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException
* 按照參數sysCode指定的編碼規范,基於位元組流in構造輸入字元流,如果不支持參數sysCode中指定的編碼規范,就會產生異常。
* public OutputStreamWriter(OutputStream out)
* 根據當前平台預設的編碼規范,基於位元組流out生成一個輸入字元流。
* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException
* 按照參數sysCode指定的編碼規范,基於位元組流out構造輸入字元流,如果不支持參數sysCode中指定的編碼規范,就會產生異常。
* public String getEncoding()
* 獲得當前字元流使用的編碼方式。
* public void close() throws IOException
* 用於關閉流。
* public int read() throws IOException
* 用於讀取一個字元。
* public int read(char[] cbuf, int off, int len)
* 用於讀取len個字元到數組cbuf的索引off處。
* public void write(char[] cbuf, int off, int len) throws IOException
* 將字元數組cbuf中從索引off處開始的len個字元寫入輸出流。
* public void write(int c) throws IOException
* 將單個字元寫入輸入流。
* public void write(String str, int off, int len) throws IOException
* 將字元串str中從索引off位置開始的ltn個字元寫入輸出流。
*
* 此外,為了提高字元流處理的效率,在Java語言中,引入了BufferedReader和BufferWriter類,這兩個類對字元流進行塊處理。
* 兩個類的常用方法如下:
* public BufferedReader(Reader in)
* 用於基於普通字元輸入流in生成相應的緩沖流。
* public BufferedReader(Reader in, int bufSize)
* 用於基於普通字元輸入流in生成相應的緩沖流,緩沖區大小為參數bufSize指定。
* public BufferedWriter(Writer out)
* 用於基於普通字元輸入流out生成相應的緩沖流。
* public BufferedWriter(Writer out, int bufSize)
* 用於基於普通字元輸入流out生在相應緩沖流,緩沖流大小為參數bufSize指定。
* public String readLine() throws IOException
* 用於從輸入流中讀取一行字元。
* public void newLine() throws IOException
* 用於向字元輸入流中寫入一行結束標記,值得注意的是,該標記不是簡單的換行符"\n",而是系統定義的屬性line.separator。
在上面的程序中,我們首先聲明了FileInputStream類對象inStream和
* FileOutputStream類的對象outStream,接著聲明了BufferInputStream
* 類對象bufObj、BufferedOutputStream類對象bufOutObj、
* DataInputStream類對象dataInObj以及PushbackInputStream類對象pushObj,
* 在try代碼塊中對上面這些對象進行初始化,程序的目的是通過BufferedInputStream
* 類對象bufInObj和BufferedOutputStream類對象bufOutObj將secondFile.txt
* 文件中內容輸出到屏幕,並將該文件的內容寫入thirdFile.txt文件中,值得注意的是,
* 將secondFile.txt文件中的內容輸出之前,程序中使用
* "System.out.println(dataInObj.readBoolean());" 語句根據readBoolean()結果
* 輸出了true,而secondFile.txt文件開始內容為「Modify」,和一個字元為M,
* 因此輸出的文件內容沒有「M」字元,thirdFile.txt文件中也比secondFile.txt
* 文件少第一個字元「M」。隨後,通過PushbackInputStream類對象pushObj讀取
* thirdFile.txt文件中的內容,輸出讀到的字元,當讀到的不是字元,輸出回車,將字元
* 數組pushByte寫回到thirdFile.txt文件中,也就是「ok」寫迴文件中。
* 對象串列化
* 對象通過寫出描述自己狀態的數值來記錄自己,這個過程叫做對象串列化。對象的壽命通
* 常是隨著生成該對象的程序的終止而終止,在有些情況下,需要將對象的狀態保存下來,然後
* 在必要的時候將對象恢復,值得注意的是,如果變數是另一個對象的引用,則引用的對象也要
* 串列化,串列化是一個遞歸的過程,可能會涉及到一個復雜樹結構的串列化,比如包括原有對
* 象,對象的對象等。
* 在java.io包中,介面Serializable是實現對象串列化的工具,只有實現了Serializable
* 的對象才可以被串列化。Serializable介面中沒有任何的方法,當一個類聲明實現Seriali-
* zable介面時,只是表明該類遵循串列化協議,而不需要實現任何特殊的方法。
* 在進行對象串列化時,需要注意將串列化的對象和輸入、輸出流聯系起來,首先通過對
* 象輸出流將對象狀態保存下來,然後通過對象輸入流將對象狀態恢復。
『柒』 java讀取文件操作
while(line != null)
{
System.out.println(line);
output.write(line);
output.newLine();
line = br.readLine();
}
output.flush();
output.close();
如果沒有flush,寫入的數據可能不完整。循環完以後加上這兩句即可
『捌』 java對文件讀寫操作,文件大小有限制么
你如果是要一次讀完一個文件的話,應該會有大小限制。
一般情況下,打比方,你有個100MB的文件,你並不是一次讀完,而是分塊,10MB一次的讀取,所以文件大小不會有限制。
『玖』 java中如何使用緩沖區對文件進行讀寫操作
首先,了解下什麼是緩沖區:
電腦內存分成5個區,他們分別是堆、棧、自由存儲區、全局/靜態存儲區和常量存儲區。
棧——就是那些由編譯器在需要的時候分配,在不需要的時候自動清楚的變數的存儲區。裡面的變數通常是局部變數、函數參數等。
堆——就是那些由new分配的內存塊,他們的釋放編譯器不去管,由我們的應用程序去控制,一般一個new就要對應一個delete.如果程序員沒有釋放掉,那麼在程序結束後,操作系統會自動回收。
自由存儲區——就是那些由malloc等分配的內存塊,他和堆是十分相似的,不過它是用free來結束自己的生命的。
全局/靜態存儲區——全局變數和靜態變數被分配到同一塊內存中,在以前的C語言中,全局變數又分為初始化的和未初始化的,在C++裡面沒有這個區分了,他們共同佔用同一塊內存區。
常量存儲區,這是一塊比較特殊的存儲區,他們裡面存放的是常量,不允許修改(當然,你要通過非正當手段也可以修改)
電腦緩沖區就是預留下來的做為急用的那一部分,為暫時置放輸出或輸入資料的內存。
如何對緩沖區進行操作:
當我們讀寫文本文件的時候,採用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。其中最重要的類是InputStreamReader, 它是位元組轉換為字元的橋梁。你可以在構造器重指定編碼的方式,如果不指定的話將採用底層操作系統的默認編碼方式,例如GBK等。使用FileReader讀取文件:
FileReader fr = new FileReader("ming.txt");
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch);
}
其中read()方法返回的是讀取得下個字元。當然你也可以使用read(char[] ch,int off,int length)這和處理二進制文件的時候類似。
事實上在FileReader中的方法都是從InputStreamReader中繼承過來的。read()方法是比較好費時間的,如果為了提高效率我們可以使用BufferedReader對Reader進行包裝,這樣可以提高讀取得速度,我們可以一行一行的讀取文本,使用readLine()方法。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
了解了FileReader操作使用FileWriter寫文件就簡單了,這里不贅述。
Eg.我的綜合實例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class testFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// file(內存)----輸入流---->【程序】----輸出流---->file(內存)
File file = new File("d:/temp", "addfile.txt");
try {
file.createNewFile(); // 創建文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 向文件寫入內容(輸出流)
String str = "親愛的小南瓜!";
byte bt[] = new byte[1024];
bt = str.getBytes();
try {
FileOutputStream in = new FileOutputStream(file);
try {
in.write(bt, 0, bt.length);
in.close();
// boolean success=true;
// System.out.println("寫入文件成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 讀取文件內容 (輸入流)
FileInputStream out = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(out);
int ch = 0;
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
『拾』 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類),從而可以實現讀寫文件中任何位置中的數據(只需要改變文件的讀寫位置的指針)。
隨機文件讀寫編程的基本過程為:
① 生成流對象並且指明讀寫類型;
② 移動讀寫位置;
③ 讀寫文件內容;
④ 關閉文件。
七里河團隊答疑助人,希望我的回答對你有所幫助