首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java io 多种资料操作方式(字节、字符、行、随机)

2013-07-11 
java io 多种文件操作方式(字节、字符、行、随机)一、多种方式读文件内容。【参考:http://www.ibm.com/developer

java io 多种文件操作方式(字节、字符、行、随机)

一、多种方式读文件内容。【参考:http://www.ibm.com/developerworks/cn/java/j-lo-javaio/】

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容

001import java.io.BufferedReader;002import java.io.File;003import java.io.FileInputStream;004import java.io.FileReader;005import java.io.IOException;006import java.io.InputStream;007import java.io.InputStreamReader;008import java.io.RandomAccessFile;009import java.io.Reader; 010public class ReadFromFile {011/**012???* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。013???* @param fileName 文件的名014???*/015public static void readFileByBytes(String fileName){016???File file = new File(fileName);017???InputStream in = null;018???try {019????System.out.println("以字节为单位读取文件内容,一次读一个字节:");020????// 一次读一个字节021????in = new FileInputStream(file);022????int tempbyte;023????while((tempbyte=in.read()) != -1){024?????System.out.write(tempbyte);025????}026????in.close();027???} catch (IOException e) {028????e.printStackTrace();029????return;030???}031???try {032????System.out.println("以字节为单位读取文件内容,一次读多个字节:");033????//一次读多个字节034????byte[] tempbytes = new byte[100];035????int byteread = 0;036????in = new FileInputStream(fileName);037????ReadFromFile.showAvailableBytes(in);038????//读入多个字节到字节数组中,byteread为一次读入的字节数039????while ((byteread = in.read(tempbytes)) != -1){040?????System.out.write(tempbytes, 0, byteread);041????}042???} catch (Exception e1) {043????e1.printStackTrace();044???} finally {045????if (in != null){046?????try {047??????in.close();048?????} catch (IOException e1) {049?????}050????}051???}052}053/**054???* 以字符为单位读取文件,常用于读文本,数字等类型的文件055???* @param fileName 文件名056???*/057public static void readFileByChars(String fileName){058???File file = new File(fileName);059???Reader reader = null;060???try {061????System.out.println("以字符为单位读取文件内容,一次读一个字节:");062????// 一次读一个字符063????reader = new InputStreamReader(new FileInputStream(file));064????int tempchar;065????while ((tempchar = reader.read()) != -1){066?????//对于windows下,/r/n这两个字符在一起时,表示一个换行。067?????//但如果这两个字符分开显示时,会换两次行。068?????//因此,屏蔽掉/r,或者屏蔽/n。否则,将会多出很多空行。069?????if (((char)tempchar) != '/r'){070??????System.out.print((char)tempchar);071?????}072????}073????reader.close();074???} catch (Exception e) {075????e.printStackTrace();076???}077???try {078????System.out.println("以字符为单位读取文件内容,一次读多个字节:");079????//一次读多个字符080????char[] tempchars = new char[30];081????int charread = 0;082????reader = new InputStreamReader(new FileInputStream(fileName));083????//读入多个字符到字符数组中,charread为一次读取字符数084????while ((charread = reader.read(tempchars))!=-1){085?????//同样屏蔽掉/r不显示086?????if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != '/r')){087??????System.out.print(tempchars);088?????}else{089??????for (int i=0; i<charread; i++){090???????if(tempchars[i] == '/r'){091????????continue;092???????}else{093????????System.out.print(tempchars[i]);094???????}095??????}096?????}097????}098????099???} catch (Exception e1) {100????e1.printStackTrace();101???}finally {102????if (reader != null){103?????try {104??????reader.close();105?????} catch (IOException e1) {106?????}107????}108???}109}110/**111???* 以行为单位读取文件,常用于读面向行的格式化文件112???* @param fileName 文件名113???*/114public static void readFileByLines(String fileName){115???File file = new File(fileName);116???BufferedReader reader = null;117???try {118????System.out.println("以行为单位读取文件内容,一次读一整行:");119????reader = new BufferedReader(new FileReader(file));120????String tempString = null;121????int line = 1;122????//一次读入一行,直到读入null为文件结束123????while ((tempString = reader.readLine()) != null){124?????//显示行号125?????System.out.println("line " + line + ": " + tempString);126?????line++;127????}128????reader.close();129???} catch (IOException e) {130????e.printStackTrace();131???} finally {132????if (reader != null){133?????try {134??????reader.close();135?????} catch (IOException e1) {136?????}137????}138???}139}140/**141???* 随机读取文件内容142???* @param fileName 文件名143???*/144public static void readFileByRandomAccess(String fileName){145???RandomAccessFile randomFile = null;146???try {147????System.out.println("随机读取一段文件内容:");148????// 打开一个随机访问文件流,按只读方式149????randomFile = new RandomAccessFile(fileName, "r");150????// 文件长度,字节数151????long fileLength = randomFile.length();152????// 读文件的起始位置153????int beginIndex = (fileLength > 4) ? 4 : 0;154????//将读文件的开始位置移到beginIndex位置。155????randomFile.seek(beginIndex);156????byte[] bytes = new byte[10];157????int byteread = 0;158????//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。159????//将一次读取的字节数赋给byteread160????while ((byteread = randomFile.read(bytes)) != -1){161?????System.out.write(bytes, 0, byteread);162????}163???} catch (IOException e){164????e.printStackTrace();165???} finally {166????if (randomFile != null){167?????try {168??????randomFile.close();169?????} catch (IOException e1) {170?????}171????}172???}173}174/**175???* 显示输入流中还剩的字节数176???* @param in177???*/178private static void showAvailableBytes(InputStream in){179???try {180????System.out.println("当前字节输入流中的字节数为:" + in.available());181???} catch (IOException e) {182????e.printStackTrace();183???}184}185?186public static void main(String[] args) {187???String fileName = "C:/temp/newTemp.txt";188???ReadFromFile.readFileByBytes(fileName);189???ReadFromFile.readFileByChars(fileName);190???ReadFromFile.readFileByLines(fileName);191???ReadFromFile.readFileByRandomAccess(fileName);192}193}

?

二、将内容追加到文件尾部

查看源码打印?001import java.io.FileWriter;002import java.io.IOException;003import java.io.RandomAccessFile;004?005/**006* 将内容追加到文件尾部007*/008public class AppendToFile {009?010/**011???* A方法追加文件:使用RandomAccessFile012???* @param fileName 文件名013???* @param content 追加的内容014???*/015public static void appendMethodA(String fileName, String content){016???try {017????// 打开一个随机访问文件流,按读写方式018????RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");019????// 文件长度,字节数020????long fileLength = randomFile.length();021????//将写文件指针移到文件尾。022????randomFile.seek(fileLength);023????randomFile.writeBytes(content);024????randomFile.close();025???} catch (IOException e){026????e.printStackTrace();027???}028}029/**030???* B方法追加文件:使用FileWriter031???* @param fileName032???* @param content033???*/034public static void appendMethodB(String fileName, String content){035???try {036????//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件037????FileWriter writer = new FileWriter(fileName, true);038????writer.write(content);039????writer.close();040???} catch (IOException e) {041????e.printStackTrace();042???}043}044?045public static void main(String[] args) {046???String fileName = "C:/temp/newTemp.txt";047???String content = "new append!";048???//按方法A追加文件049???AppendToFile.appendMethodA(fileName, content);050???AppendToFile.appendMethodA(fileName, "append end. /n");051???//显示文件内容052???ReadFromFile.readFileByLines(fileName);053???//按方法B追加文件054???AppendToFile.appendMethodB(fileName, content);055???AppendToFile.appendMethodB(fileName, "append end. /n");056???//显示文件内容057???ReadFromFile.readFileByLines(fileName);058}059}060?061三文件的各种操作类062?063import java.io.*;064?065/**066* FileOperate.java067* 文件的各种操作068* @author 杨彩 http://blog.sina.com.cn/m/yangcai069* 文件操作 1.0070*/071?072public class FileOperate073{074?075public FileOperate()076{077}078/**079* 新建目录080*/081public void newFolder(String folderPath)082{083try084{085String filePath = folderPath;086filePath = filePath.toString();087File myFilePath = new File(filePath);088if(!myFilePath.exists())089{090myFilePath.mkdir();091}092System.out.println("新建目录操作 成功执行");093}094catch(Exception e)095{096System.out.println("新建目录操作出错");097e.printStackTrace();098}099}100/**101* 新建文件102*/103public void newFile(String filePathAndName, String fileContent)104{105try106{107String filePath = filePathAndName;108filePath = filePath.toString();109File myFilePath = new File(filePath);110if (!myFilePath.exists())111{112myFilePath.createNewFile();113}114FileWriter resultFile = new FileWriter(myFilePath);115PrintWriter myFile = new PrintWriter(resultFile);116String strContent = fileContent;117myFile.println(strContent);118resultFile.close();119System.out.println("新建文件操作 成功执行");120}121catch (Exception e)122{123System.out.println("新建目录操作出错");124e.printStackTrace();125}126}127/**128* 删除文件129*/130public void delFile(String filePathAndName)131{132try133{134String filePath = filePathAndName;135filePath = filePath.toString();136File myDelFile = new File(filePath);137myDelFile.delete();138System.out.println("删除文件操作 成功执行");139}140catch (Exception e)141{142System.out.println("删除文件操作出错");143e.printStackTrace();144}145}146/**147* 删除文件夹148*/149public void delFolder(String folderPath)150{151try152{153delAllFile(folderPath); //删除完里面所有内容154String filePath = folderPath;155filePath = filePath.toString();156File myFilePath = new File(filePath);157if(myFilePath.delete()) { //删除空文件夹158System.out.println("删除文件夹" + folderPath + "操作 成功执行");159} else {160System.out.println("删除文件夹" + folderPath + "操作 执行失败");161}162}163catch (Exception e)164{165System.out.println("删除文件夹操作出错");166e.printStackTrace();167}168}169/**170* 删除文件夹里面的所有文件171* @param path String 文件夹路径 如 c:/fqf172*/173public void delAllFile(String path)174{175File file = new File(path);176if(!file.exists())177{178return;179}180if(!file.isDirectory())181{182return;183}184String[] tempList = file.list();185File temp = null;186for (int i = 0; i < tempList.length; i++)187{188if(path.endsWith(File.separator))189{190temp = new File(path + tempList[i]);191}192else193{194temp = new File(path + File.separator + tempList[i]);195}196if (temp.isFile())197{198temp.delete();199}200if (temp.isDirectory())201{202//delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件203delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹204}205}206System.out.println("删除文件操作 成功执行");207}208/**209* 复制单个文件210* @param oldPath String 原文件路径 如:c:/fqf.txt211* @param newPath String 复制后路径 如:f:/fqf.txt212*/213public void copyFile(String oldPath, String newPath)214{215try216{217int bytesum = 0;218int byteread = 0;219File oldfile = new File(oldPath);220if (oldfile.exists())221{222//文件存在时223InputStream inStream = new FileInputStream(oldPath); //读入原文件224FileOutputStream fs = new FileOutputStream(newPath);225byte[] buffer = new byte[1444];226while ( (byteread = inStream.read(buffer)) != -1)227{228bytesum += byteread; //字节数 文件大小229System.out.println(bytesum);230fs.write(buffer, 0, byteread);231}232inStream.close();233}234System.out.println("删除文件夹操作 成功执行");235}236catch (Exception e)237{238System.out.println("复制单个文件操作出错");239e.printStackTrace();240}241}242/**243* 复制整个文件夹内容244* @param oldPath String 原文件路径 如:c:/fqf245* @param newPath String 复制后路径 如:f:/fqf/ff246*/247public void copyFolder(String oldPath, String newPath)248{249try250{251(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹252File a=new File(oldPath);253String[] file=a.list();254File temp=null;255for (int i = 0; i < file.length; i++)256{257if(oldPath.endsWith(File.separator))258{259temp=new File(oldPath+file[i]);260}261else262{263temp=new File(oldPath+File.separator+file[i]);264}265if(temp.isFile())266{267FileInputStream input = new FileInputStream(temp);268FileOutputStream output = new FileOutputStream(newPath + "/" +269(temp.getName()).toString());270byte[] b = new byte[1024 * 5];271int len;272while ( (len = input.read(b)) != -1)273{274output.write(b, 0, len);275}276output.flush();277output.close();278input.close();279}280if(temp.isDirectory())281{282//如果是子文件夹283copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);284}285}286System.out.println("复制文件夹操作 成功执行");287}288catch (Exception e)289{290System.out.println("复制整个文件夹内容操作出错");291e.printStackTrace();292}293}294/**295* 移动文件到指定目录296* @param oldPath String 如:c:/fqf.txt297* @param newPath String 如:d:/fqf.txt298*/299public void moveFile(String oldPath, String newPath)300{301copyFile(oldPath, newPath);302delFile(oldPath);303}304/**305* 移动文件到指定目录306* @param oldPath String 如:c:/fqf.txt307* @param newPath String 如:d:/fqf.txt308*/309public void moveFolder(String oldPath, String newPath)310{311copyFolder(oldPath, newPath);312delFolder(oldPath);313}314public static void main(String args[])315{316String aa,bb;317boolean exitnow=false;318System.out.println("使用此功能请按[1] 功能一:新建目录");319System.out.println("使用此功能请按[2] 功能二:新建文件");320System.out.println("使用此功能请按[3] 功能三:删除文件");321System.out.println("使用此功能请按[4] 功能四:删除文件夹");322System.out.println("使用此功能请按[5] 功能五:删除文件夹里面的所有文件");323System.out.println("使用此功能请按[6] 功能六:复制文件");324System.out.println("使用此功能请按[7] 功能七:复制文件夹的所有内容");325System.out.println("使用此功能请按[8] 功能八:移动文件到指定目录");326System.out.println("使用此功能请按[9] 功能九:移动文件夹到指定目录");327System.out.println("使用此功能请按[10] 退出程序");328while(!exitnow)329{330FileOperate fo=new FileOperate();331try332{333BufferedReader Bin=new BufferedReader(new InputStreamReader(System.in));334String a=Bin.readLine();335int b=Integer.parseInt(a);336switch(b)337{338case 1:System.out.println("你选择了功能一 请输入目录名");339aa=Bin.readLine();340fo.newFolder(aa);341break;342case 2:System.out.println("你选择了功能二 请输入文件名");343aa=Bin.readLine();344System.out.println("请输入在"+aa+"中的内容");345bb=Bin.readLine();346fo.newFile(aa,bb);347break;348case 3:System.out.println("你选择了功能三 请输入文件名");349aa=Bin.readLine();350fo.delFile(aa);351break;352case 4:System.out.println("你选择了功能四 请输入文件名");353aa=Bin.readLine();354fo.delFolder(aa);355break;356case 5:System.out.println("你选择了功能五 请输入文件名");357aa=Bin.readLine();358fo.delAllFile(aa);359break;360case 6:System.out.println("你选择了功能六 请输入文件名");361aa=Bin.readLine();362System.out.println("请输入目标文件名");363bb=Bin.readLine();364fo.copyFile(aa,bb);365break;366case 7:System.out.println("你选择了功能七 请输入源文件名");367aa=Bin.readLine();368System.out.println("请输入目标文件名");369bb=Bin.readLine();370fo.copyFolder(aa,bb);371break;372case 8:System.out.println("你选择了功能八 请输入源文件名");373aa=Bin.readLine();374System.out.println("请输入目标文件名");375bb=Bin.readLine();376fo.moveFile(aa,bb);377break;378case 9:System.out.println("你选择了功能九 请输入源文件名");379aa=Bin.readLine();380System.out.println("请输入目标文件名");381bb=Bin.readLine();382fo.moveFolder(aa,bb);383break;384case 10:exitnow=true;385System.out.println("程序结束,请退出");386break;387default:System.out.println("输入错误.请输入1-10之间的数");388}389System.out.println("请重新选择功能");390}391catch(Exception e)392{393System.out.println("输入错误字符或程序出错");394}395}396}397}

热点排行