慕课网5 文件传输基础
生活随笔
收集整理的這篇文章主要介紹了
慕课网5 文件传输基础
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.radix 文件的編碼
public class radix {/*** @param args*/public static void main(String[] args) throws Exception{// TODO Auto-generated method stub/** 文本文件 就是字節序列* 可以使任意編碼的字節序列* 中文機器上直接創建文件,文本文件 只認識ANSI編碼,直接粘貼的全認識* 聯通、聯想是一種巧合,正好符合了utf-8的規則*/String s="慕課ABC";//默認gbk 中文兩個字節 英文一個字節byte[] bytes1=s.getBytes();for(byte b:bytes1){ System.out.print(Integer.toHexString(b&0xff)+" "); //c4 bd bf ce 41 42 43 }//utf-8 中文三個字節 英文一個字節System.out.println();byte[] bytes2=s.getBytes("utf-8");for(byte b:bytes2){System.out.print(Integer.toHexString(b&0xff)+" "); //e6 85 95 e8 af be 41 42 43}//JAVA是雙字節編碼 utf-16be 中文英文兩個字節System.out.println();byte[] bytes3=s.getBytes("utf-16be");for(byte b:bytes3){ System.out.print(Integer.toHexString(b&0xff)+" "); //61 55 8b fe 0 41 0 42 0 43 }/** 當你的字節序列是某種編碼時,轉換為字符串時也需要用這種編碼方式*/String s2=new String(bytes2);System.out.print(s2);String s3=new String(bytes2,"utf-8");System.out.print(s3); } }2.FileDemo File類的使用
import java.io.File; import java.io.IOException;public class FileDemo {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub /** java.io.File類用于表示文件(目錄)* File類只用于表示文件(目錄)的信息(名稱),不能直接用于文件內容的訪問*///了解構造函數的情況 alt+/查看幫助File file=new File("D:\\A");if(!file.exists()) //不存在file.mkdir(); //創建目錄 mkdirs創建多級目錄/*elsefile.delete(); //刪除目錄*/ System.out.println(file.isDirectory()); //是否是目錄System.out.println(file.isFile());//是否是文件//File file2=new File("D:\\A\\A1.txt");File file2=new File("D:\\A","A1.txt");if(!file2.exists()) //不存在{try{file2.createNewFile();}catch(IOException e){e.printStackTrace();}}else{file2.delete();}//常用File對象的APISystem.out.println(file); //D:\ASystem.out.println(file.getAbsolutePath()); //D:\ASystem.out.println(file.getName()); //ASystem.out.println(file2.getName()); //A1.txtSystem.out.println(file.getParent()); //D:\System.out.println(file2.getParent()); //D:\ASystem.out.println(file.getParentFile().getAbsolutePath()); //D:\}}3.FileUtil ? ?遍歷目錄
import java.io.File;//列出File的一些常用操作如過濾.遍歷等 public class FileUtil {/*** 列出指定目錄下(包括其子目錄)的所有文件* * @param dir* @throws Exception*/public static void listDirectoy(File dir) throws Exception {if (!dir.exists()) {throw new IllegalArgumentException("目錄" + dir + "不存在");} else if (!dir.isDirectory()) {throw new IllegalArgumentException(dir + "不是目錄");}// 子文件或目錄名稱,不包含子目錄下的名稱String[] names = dir.list();for (String name : names) {System.out.println(name);}// 如果要遍歷子目錄下的內容就需要構造成File對象做遞歸操作File[] files = dir.listFiles();if (files != null && files.length > 0) {for (File file : files) {if (file.isDirectory()) {listDirectoy(file); // 遞歸} else {System.out.println(file);}}}}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubtry {FileUtil.listDirectoy(new File("D:\\"));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}4.RandomAccessFile類的使用
/*RandomAccessFile java提供對文件內容的訪問,既可以讀文件,也可以寫文件。*RandomAccessFile支持隨機訪問文件,可以訪問文件的任意位置**1)JAVA文件模型* 在硬盤上的文件時byte存儲的,是數據的集合*2)打開文件 * 兩種模式 rw (讀寫),r(只讀)*RandomAccessFile raf=new RandomAccessFile(file,"rw");*文件指針,打開文件時指針在開頭pointer=0;*3)寫方法*raf.write(int)-->只寫一個字節(后8位),同時指針指向下一個字節位置*4)讀方法*raf.read()-->讀一個字節*5)關閉文件*/ import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; public class RandomAccessFileDemo {/*** @param args* @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubFile demo=new File("demo");//相對路徑,項目下if(!demo.exists()){demo.mkdir();}File file=new File(demo,"raf.dat");if(!file.exists()){file.createNewFile();}RandomAccessFile raf =new RandomAccessFile(file,"rw");//指針的位置System.out.println(raf.getFilePointer()); //0 //用write只寫了一個字節raf.write('A'); System.out.println(raf.getFilePointer()); //1raf.write('B');System.out.println(raf.getFilePointer()); //2//可以writeInt直接寫一個intint i=0x7fffffff;raf.writeInt(i);System.out.println(raf.getFilePointer()); //6String s="中"; //utf-16bebyte[] gbk=s.getBytes();raf.write(gbk);System.out.println(raf.getFilePointer()); //8//讀文件,必須把指針移到頭部raf.seek(0);//一次性讀取,把文件中的內容都讀到字節數組中byte[]buf=new byte[(int)raf.length()];raf.read(buf);System.out.println(Arrays.toString(buf));//[65, 66, 127, -1, -1, -1, -42, -48, 45]for(byte b:buf){System.out.println(Integer.toHexString(b)); //十六進制輸出}String s1=new String(buf);System.out.println(s1); //AB???//關閉文件raf.close();}}5.字節流 ?InputStream、OutputStream ?FIleInputStream/?FIleOutputStream
BufferedInputStream/BufferedOutputoutStream
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;/** IO流(輸入流,輸出流)* 字節流、字符流* 1.字節流* 1)InputStream、OutputStream 抽象類* InputStream抽象了應用程序讀取數據的方式* OutputStream抽象了應用程序寫出數據的方式* 2)EOF=End 讀到-1就讀到結尾* 3)輸入流基本方法* int b=in.read(); //讀取一個字節無符號填充到整形的低8位。-1是EOF* in.read(byte[] buf);* in.read(byte[] buf,int start,int size);*4)輸出流基本方法* out.write(int b)//寫出一個byte到流,低8位* out.write(byte[] buf) //將byte字節數組都寫入到流* out.write(byte[] buf,int start,int size);*5) FIleInputStream繼承InputStream,具體實現了在文件上讀取 *6) FIleOutputStream實現了向文件中寫出byte數據的方法*//** BufferedInputStream/BufferedOutputoutStream* 這兩個流為IO提供了帶緩沖區的操作,一般打開文件進行寫入* 或讀取操作時,都會加入緩沖,這種流模式提高了IO的性能* 從應用程序中把輸入放入文件,相當將一缸水倒入另一個缸中* FileOutputStream-->wrie()方法相當于一滴滴轉移* DataOutputStream-->writeXXx()方法,相當于一瓢瓢轉移* BufferedOutputStream-->wrie()方法,相當將一瓢瓢先放入桶,再從桶倒入缸中*/public class FileInputDemo {/*讀取制定文件內容,按照16進制輸出*每輸出10個換行*單字節讀取不適合大文件*/public static void printHex(String fileName) throws IOException{//把文件作為字節流進行讀操作FileInputStream in=new FileInputStream(fileName);int b;int i=1;while((b=in.read())!=-1){if(b<=0xf){//單位數前面補0System.out.print("0");}System.out.print(Integer.toHexString(b)+" ");if((i++)%10==0)System.out.println();}System.out.println();in.close(); //關閉操作}/*** 大文件適于批量讀取* @param fileName* @throws IOException*/public static void printHexByByteArray(String fileName) throws IOException{FileInputStream in=new FileInputStream(fileName);byte[] buf=new byte[20*1024];/*//從In中批量讀取字節,從第0個位子開始放,最多放buf.length個,返回讀取字節個數int bytes=in.read(buf, 0, buf.length);//若一次性讀完,說明buf足夠大 for(int i=0;i<bytes;i++){if(buf[i]<=0xf){//單位數前面補0System.out.print("0");}System.out.print(Integer.toHexString(buf[i])+" ");if((i+1)%10==0)System.out.println();}*///有可能一次性讀不完 int bytes=0;while((bytes=in.read(buf, 0, buf.length))!=-1){for(int i=0;i<bytes;i++){if(buf[i]<=0xf){//單位數前面補0System.out.print("0");}System.out.print(Integer.toHexString(buf[i])+" ");if((i+1)%10==0)System.out.println();}}System.out.println();in.close();}/*** 文件拷貝,批量讀取,最快* @param srcFile* @param desrFile* @throws IOException*/public static void copyFile(File srcFile,File destFile) throws IOException{if(!srcFile.exists()){throw new IllegalArgumentException("文件不存在");}if(!srcFile.isFile()){throw new IllegalArgumentException("文件不存在");}FileInputStream in = new FileInputStream(srcFile);FileOutputStream out = new FileOutputStream(destFile);byte[] buf=new byte[8*1024];int bytes;while((bytes=in.read(buf, 0, buf.length))!=-1){out.write(buf, 0, bytes);out.flush(); //帶緩沖區要刷新}in.close();out.close(); }/*** 文件拷貝,單字節讀取,最慢* @param srcFile* @param desrFile* @throws IOException*/public static void copyFileByByte(File srcFile,File destFile) throws IOException{if(!srcFile.exists()){throw new IllegalArgumentException("文件不存在");}if(!srcFile.isFile()){throw new IllegalArgumentException("文件不存在");}FileInputStream in = new FileInputStream(srcFile);FileOutputStream out = new FileOutputStream(destFile); int bytes;while((bytes=in.read())!=-1){out.write(bytes);}in.close();out.close();}/** 帶有緩沖區的讀取*/public static void copyFileByBuffered(File srcFile,File destFile) throws IOException{if(!srcFile.exists()){throw new IllegalArgumentException("文件不存在");}if(!srcFile.isFile()){throw new IllegalArgumentException("文件不存在");}BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));int b;while((b=bis.read())!=-1){bos.write(b);bos.flush();//帶緩沖區要刷新}bis.close();bos.close();}/*** @param args* @throws IOException * @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubtry {FileInputDemo.printHex("demo\\raf.txt");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {long start=System.currentTimeMillis();FileInputDemo.printHexByByteArray("demo\\raf.txt");long end=System.currentTimeMillis();System.out.println(end-start);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//如果該文件不存在,則直接創建,如果存在,刪除后刪除重建//若第二個參數為true,則appendFileOutputStream out=new FileOutputStream("demo\\raf.txt");out.write('A'); //低8位out.write('B');byte[] gbk="中國".getBytes("gbk");out.write(gbk);FileInputDemo.printHex("demo\\raf.txt");FileInputDemo.copyFile(new File("demo\\raf.txt"),new File( "demo\\raf1.txt"));}}6.DataOutputStream、DataInputStream?
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;/** DataInputStream / DataOutputStream* 對“流”功能的擴展,可以更加方面的讀取int,long,字符等類型數據* DataOutputStream* writeInt()/writeDouble/writeUTF()*/ public class DataInputDemo {/*** @param args*/public static void main(String[] args) throws IOException{// TODO Auto-generated method stubString file="demo\\raf.txt";//DataOutputStreamDataOutputStream dos=new DataOutputStream(new FileOutputStream(file));dos.writeInt(10);dos.writeLong(10l);dos.writeDouble(10.5);//采用utf-8編碼寫出dos.writeUTF("中國");//采用utf-16be編碼寫出dos.writeChars("中國");dos.close();//DataInputStreamDataInputStream dis=new DataInputStream(new FileInputStream(file));int i=dis.readInt();System.out.println(i);long l=dis.readLong();System.out.println(l);double d=dis.readDouble();System.out.println(d);String s=dis.readUTF();System.out.println(s);}}7.字符流 ?InputStreamReader/OutputStreamReader ??BufferedReader ?BufferedWriter/PrintWriter
<p><span style="font-size:14px;"> /** 字符流* 1)編碼問題* 2)認識文本和文本文件* JAVA的文本(char)是16位無符號整數,是自負的unicode編碼(雙字節編碼)* 文件是byte byte byte---的數據序列* 文本文件是文本(char)序列按照某種編碼方案(utf-8,.utf-16be,gbk)序列化為byte的存儲* 3)字符流(Reader Writer)* 字符的</span>處理,一次處理一個字符</p> * 字符的底層仍然是基本的字符序列* 字符流的基本實現* InputStreamReader 完成byte流解析為char流,按照編碼解析* OutputStreamReader 提供char流到byte流,按照編碼處理* 4)FileReader FileWriter * 5)字符流的過濾器* BufferedReader -->readLine()一次讀取一行* BufferedWriter/PrintWriter --寫一行*/ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; public class InputStreamReaderDemo {/*** @param args* @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stub//字節字符轉換流InputStreamReader isr=new InputStreamReader(new FileInputStream("demo\\raf.txt"),"gbk");OutputStreamWriter osr=new OutputStreamWriter(new FileOutputStream("demo\\raf3.txt"));int c;/*while((c=isr.read())!=-1){System.out.print((char)c);osr.write(c);}*///批量讀取char []buf=new char[8*1024];while((c=isr.read(buf, 0, buf.length))!=-1){String s=new String(buf,0,c);System.out.print(s);osr.write(buf,0, c);osr.flush(); }isr.close();osr.close();//字符流之文件讀寫流FileReader fr=new FileReader("demo\\raf.txt");FileWriter fw=new FileWriter("demo\\raf4.txt");char []buffer=new char[8*1024];while((c=fr.read(buffer, 0, buffer.length))!=-1){fw.write(buffer,0, c);fw.flush(); }fr.close();fw.close();//字符流的過濾器BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("demo\\raf.txt")));//BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("demo\\raf5.txt")));PrintWriter pw=new PrintWriter("demo\\raf5.txt");String line;while((line=br.readLine())!=null){/*bw.write(line);bw.newLine();bw.flush();*/pw.println(line);pw.flush();}br.close();pw.close();}}
8.序列化和反序列化 /*** 對象的序列化和反序列化* 1)將Object轉換成byte序列,反之為對象的反序列化* 2)序列化流(ObjectOutputStream) ---->writeObject* 反序列化流(ObjectInputStream) ---->readObject* 3)序列化接口(Serializable)* 對象必須實現序列化接口,才能進行序列化,否則出現異常* 這個借口,沒有任何方法,只是一個標準* 4)transient關鍵字 該元素不會被進行jvm默認序列化,也可以自己完成元素的序列化* private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{}* private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException{}* 5)父類實現序列化接口,其子類都可進行初始化* 6)對子類對象進行序列化操作時,如果其父類沒有實現序列化接口,那么其父類的構造函數會被調用*/import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList;public class SeriablizableDemo implements Serializable{ //聲明Serializable接口,否則異常private String stu;private String stuname;private transient int stuage;@Overridepublic String toString() {return "SeriablizableDemo [stu=" + stu + ", stuage=" + stuage+ ", stuname=" + stuname + "]";}public SeriablizableDemo(String stu, String stuname, int stuage) {super();this.stu = stu;this.stuname = stuname;this.stuage = stuage;}private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{ //ArrayList方法名粘貼s.defaultWriteObject(); //默認s.writeInt(stuage); //自己完成}private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {s.defaultReadObject();//默認this.stuage=s.readInt(); //自己完成 }/*** @param args* @throws IOException * @throws ClassNotFoundException * @throws FileNotFoundException */public static void main(String[] args) throws IOException, ClassNotFoundException {// TODO Auto-generated method stubString file="demo\\raf6.txt"; //保存到此文件中//序列化ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));SeriablizableDemo stu=new SeriablizableDemo("張三","小",20);oos.writeObject(stu);oos.flush();oos.close();//反序列化ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));SeriablizableDemo stu2=(SeriablizableDemo)ois.readObject();System.out.println(stu2.toString());ois.close();}}
總結
以上是生活随笔為你收集整理的慕课网5 文件传输基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ESET病毒库更新提示0x210a报错
- 下一篇: SAP ABAP开发入门-徐春波-专题视