1. 문서 인코딩
package com.study.io;/*** 테스트 파일 인코딩*/public class encodedemo {/*** @param args*@throws 예외*/public static void main (string [] args)은 예외 {string s = "연구 abc well"; byte [] bytes1 = s.s.S.S.S.GETBYTES (); (Byte B : Bytes1) {// System.out.print (integer.toHexString (B & 0xff)+"" ")에 대한 (Byte B : Bytes1) {// utf-8입니다. // 0xff는 처음 24 숫자를 제거하고 마지막 8 자리} 시스템을 남기는 것입니다. 영어 */byte [] bytes2 = s.getBytes ( "utf-8"); // 여기에 예외가 표시되므로 여기에 표시 될 예정이므로 (byte b : bytes2) {system.out.print (integer.toHexString (b & 0xff)+""); 영어 */byte [] bytes3 = s.getBytes ( "gbk"); // 여기에는 예외가 표시되므로 (byte b : bytes3) {system.out.print (integer.toHexString (b & 0xff)+""); 2 바이트*/byte [] bytes4 = s.getBytes ( "utf-16be"); // 여기에는 예외가 표시되므로 (byte b : bytes4) {system.out.print (integer.toHexString (b & 0xff)+"")에 대해이 예외를 던질 것입니다. 바이트 시퀀스를 문자열로 전환하려면이 인코딩 메소드를 사용해야합니다. 그렇지 않으면 차량 코드가 표시됩니다*/String str1 = new String (bytes4); // 현재로서는 프로젝트의 기본 인코딩이 변환하는 데 사용될 수 있으며, 변형 코드는 시스템이 나타날 수 있습니다. 문자열 (bytes4, "utf-16be"); system.out.println (str2);}} 분석 :
* 1.“& 0xff”에 대한 설명 :
* 0xff는 16 진수 (10 진수 IS 255)를 나타내며 "111111111"인 이진으로 표현됩니다.
* 그런 다음 & 캐릭터는 비트 수를 나타냅니다 (동일한 경우 1은 1 인 경우 1, 그렇지 않으면 반환 0).
* 2. 바이트 바이트 및 int 유형 변환 :
* integer.tohexstring (b & 0xff) 여기, 바이트 유형의 b 및 0xff가 먼저 수행 된 다음 integer.tohexstring을 획득합니다.
* B & 0XFF의 결과는 여전히 INT라는 것을 알 수 있습니다. 왜 0XFF로 작업을 수행해야합니까? Direct Integer.toHexString (b);, int를 강제로 변환 할 수 없습니까? 대답은 불가능합니다.
* 이유는 다음과 같습니다. 1. 비트의 크기는 8 비트이고 INT의 크기는 32 비트입니다. 2. 자바의 두 보완 양식
* integer.tohexstring의 매개 변수는 int입니다. & 0xff가 수행되지 않으면 바이트가 int로 변환되면 int는 32 비트이고 바이트는 8 비트 만 가지 므로이 시간에 채워집니다. . . . . .
* 따라서 바이트와 0xff가 관련되면 바이트가 먼저 성형 수술로 변환되므로 결과의 높은 24 비트는 항상 0으로 지워 지므로 결과는 항상 원하는 것입니다.
* 3. 3.UTF-8 인코딩 : 중국어는 3 바이트를 차지하고 영어는 1 바이트를 차지합니다.
* GBK 인코딩 : 중국어는 2 바이트를 차지하고 영어는 1 바이트를 차지합니다.
* Java는 이중 바이트 인코딩 (즉, Java의 하나의 문자가 2 바이트를 차지합니다)을 사용하고 UTF-16BE 인코딩입니다. 중국어는 2 바이트를 차지하고 영어는 2 바이트를 차지합니다
*
* 4. 바이트 시퀀스가 특정 인코딩 인 경우 바이트 시퀀스를 문자열로 바꾸려면이 인코딩 메소드를 사용해야합니다. 그렇지 않으면 차량 코드가 발생합니다.
* 5. 텍스트 파일은 바이트 시퀀스입니다. 인코딩 된 바이트 시퀀스 일 수 있습니다.
* 중국 시스템에서 직접 텍스트 파일을 작성하면 파일은 ANSI 인코딩 만 인식합니다 (예 : 컴퓨터에서 직접 텍스트 파일을 만듭니다).
2. 파일 클래스 사용
package com.study.io; import java.io.file;/*** 파일 클래스 사용*/public class filedemo {/* java.io.file 클래스는 파일 또는 디렉토리를 나타냅니다. 파일 클래스는 파일 또는 디렉토리의 정보 (이름, 크기 등)의 정보를 나타내는 데만 사용되며 파일 내용에 액세스하는 데 사용할 수 없습니다. */public static void main (string [] args) {file file = new File ( "d : // 111"); // 파일 객체를 만들 때 디렉토리를 지정하기 위해 이중 슬래시를 사용해야합니다. "/"는 디렉토리의 중간에있는 분리기의 분리기를 사용하여 분리기를 설정할 수 있기 때문입니다. file ( "d :"+file.separator); // system.out.println (file.exists ()); // exists () 파일 또는 폴더가 존재하는지 여부를 결정합니다. (! file.exists ()) {// 파일이 file.mkdir () 및 mkdirs를 생성하는 경우 () directory} else {file.delete (); // 파일 또는 폴더 삭제} // 디렉토리 ISDirectory인지 여부를 감지하고 디렉토리 인 경우 true return falsesystem.out.println (file.isdirectory ()); // isfilesystem.out.println (file.isfile ()) file2 = 새 파일 ( "d : // 222", "123.txt"); // common api : system.out.println (file); // file.toString () system.out.println (file.getAbsolutepath ())의 내용을 인쇄; // 절대 경로 시스템을 얻는다. System.out.println (file2.getName ()); System.out.println (file.getParent ()); // 부모 절대 경로 시스템을 가져옵니다. 실행 결과 :
설명 :
java.io.file 클래스는 파일 또는 디렉토리를 나타냅니다
파일 클래스는 파일 또는 디렉토리의 정보 (이름, 크기 등)를 나타내는 데만 사용되며 파일 콘텐츠에 액세스하는 데 사용할 수 없습니다.
일반적으로 사용되는 API :
1. 파일 개체 생성 : 파일 = 새 파일 (String Path); 참고 : file.seperater (); "/".
2. 부울 file.exists () 여부; 존재합니다.
3.file.mkdir (); 또는 file.mkdirs (); 디렉토리 또는 다중 레벨 디렉토리를 만듭니다.
4.file.isdirectory ()는 디렉토리인지 여부를 결정합니다
file.isfile ()는 파일인지 여부를 결정합니다.
5.file.delete (); 파일 또는 디렉토리 삭제.
6.file.createnewfile (); 새 파일을 만듭니다.
7.file.getName () 파일 이름 또는 디렉토리 절대 경로를 가져옵니다.
8.file.getabsolutepath ()는 절대 경로를 가져옵니다.
9.file.getParent (); 부모의 절대 경로를 얻으십시오.
1. 디렉토리를 가로 지르십시오
package com.study.io; import java.io.file; import java.io.ioexception;/*** 파일 도구 클래스*와 같은 파일 클래스의 공통 작업을 나열합니다. 필터링, 트래버싱 등*/public class fileUtils {/***는 지정된 디렉토리에 모든 파일을 나열합니다. (하위 디렉터 포함)*/public dir*@th exmence*/exmence ListDirectory (파일 dir)는 ioexception {ioxception {if (! dir.exists ()) {// Exists () 메소드가 파일 또는 디렉토리가 새로운 불법적 인 불법 행위 렉스크 ( "dir :"+dir+"가 존재하지 않는지")를 결정하는 데 사용됩니다. diregalArgumentException (dir+"directory");}/*string [] filenames = dir.list (); list () 메소드는 현재 디렉토리에 하위 디렉터와 파일을 나열하는 데 사용됩니다 (하위 디렉터의 이름은 하위 디렉터의 내용이 포함되어 있지 않으며 문자열 배열은 (문자열)에 반환됩니다 (문자열). {system.out.println (string);}*/// 하위 디렉토리의 내용을 가로 지르려면 재귀 작업을 위해 파일 개체를 구성해야합니다. 파일은 파일 객체를 직접 반환하는 apifile을 제공합니다. listfiles = dir.listfiles (); // 직접 서브 디렉토리 (파일) if (listfiles! = null && listfiles.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.length.out.printlne.file);file.isdirectory(/file.isdirectory(//recursive)의 추상화를 반환합니다. listDirectory (file);} else {system.out.println (파일);}}}}}} 테스트 클래스 :
public class fileUtilstest {public static void main (String [] args)은 ioException {fileUtils.listDirectory (새 파일 ( "d : // iostudy"));}} 실행 결과 :
3. RandomAccessFile 클래스 사용
RandomAccessFile : Java는 파일 내용에 대한 액세스를 제공하며 파일을 읽거나 파일을 작성하는 데 사용할 수 있습니다.
RandomAccessFile은 파일에 대한 무작위 액세스를 지원하며 파일의 모든 위치에 액세스 할 수 있습니다.
Java 파일 모델에 유의하십시오.
실행 결과 :
1
12
[65, 66, 127, -1, -1, -1, 127, -1, -1, -1, -42, -48]
7f
FF
FF
FF
7f
FF
FF
FF
D6
D0
4. 바이트 스트림 (FileInputStream, FileOutputStream)
IO 스트림은 입력 스트림 및 출력 스트림으로 나눌 수 있습니다.
여기에서는 바이트 스트림과 문자 스트림으로 나눌 수 있습니다.
Code example:
package com.study.io; import java.io.bufferedInputStream; import java.io.bufferedoutputStream; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioExcept;/*** IO 도구 클래스* inpute and orerput stream : input : input : inpute and putpute 파일에 대한 데이터를 읽는다* 파일 아웃 푸트 스트림-> 파일에 바이트 데이터를 작성하는 방법의 구현* ❤data 입력 및 출력 스트림 :* DataOutputStream/DataInputStream : "스트림"기능을 확장하면 int, long, 문자 및 기타 유형의 데이터를 읽을 수 있습니다. BufferedInputStream 및 BufferedOutputStream*이 두 개의 스트림 클래스 비트 io는 버퍼와 함께 작업을 제공합니다. 일반적으로 작성 또는 읽기 작업을위한 파일을 열 때 버퍼링이 추가됩니다. 이 스트림 모드는 IO*의 성능을 향상시킵니다. 예 : 응용 프로그램에서 파일에 입력을 두는 것은 물의 실린더를 다른 실린더에 붓는 것과 동일합니다. 파일 아웃 푸트 스트림 ---> write () 메소드는 데이터 아우트 스트림을 통해 물을 전송하는 것과 동일합니다-> Writexxx () 메소드는 더 편리하고 똑같은 "Wronge" 먼저 버킷에 퍼져 (즉, 버퍼 영역), 버킷에서 다른 실린더에 붓습니다. 성능이 개선되었습니다*/public class ioutil {/*** 지정된 파일의 내용을 읽고 16 진수*에서 콘솔에 출력하십시오* @param filename* @param filename* 단일 바이트 판독 값은 큰 파일에 적합하지 않으며 큰 파일은 매우 비효율적 인*/public static void frinthex (String filename)입니다. in = new FileInputStream (filename); int b; int i = 1; while ((b = in.read ())! = -1) {/* 0xff는 2 자리 시스템으로 대체됩니다. 이는 8 1을 의미합니다. 이런 식으로, 캐릭터의 낮은 8 비트가 실제로 촬영됩니다. * OXF는 15입니다. 15보다 작은 숫자는 16 진수로 변환됩니다. * 코드는 두 개의 고정 된 16 진수 숫자가되기를 희망하므로 하나만 생성되면 0*/if (b <= 0xf) {// integer.toHexString (b)을 추가해야합니다. System.out.print (Integer.toHexString (b)+""); if (i ++%10 == 0) {system.out.println ();}} in.close (); // 파일 읽기가 닫혀 있어야합니다}/*** 배치 읽기는 큰 파일에 효율적이며 파일을 읽는 데 가장 일반적으로 사용되는 방법입니다* @param filename*/public void princecce*/public void princbytbytbytbytbytbytbytbytbyt ioException {fileInputStream in = new FileInputStream (filename); byte [] buf = new byte [8* 1024];/* 배치 읽기 바이트에서 BUF의 바이트 배열에 넣고 0 번째 위치에서 시작하여 대부분의 buf.length*를 읽습니다. in.read (buf, 0, buf.length); // 한 번에 읽으려면 바이트 배열이 충분히 크다는 것을 나타냅니다. int j = 1; for (int i = 0; i <bytes; i ++) {system.out.print (integer.tohexstring (buf [i] & 0xff)+"+" "); if (j ++%10 == 0) {system.out.println ();}}*/int bytes = 0; int j = 1; in.read (buf, 0, buf.length))! = -1) {for (int i = 0; i <bytes; i ++) {system.out.print (integer.tohexstring (buf [i] & 0xff)+"+" "; & 0xff*/if (j ++%10 == 0) {System.out.println ();}}} in.close ();}/*** 파일 사본, 바이트 배치 읽기* @param srcfile* @param destfile* @throws ioexception*/public static void copyfile (파일 파일, 파일). (! srcfile.exists ()) {throw new new ImperalArgumentException ( "파일 :" + srcfile + "존재하지 않는");} if (! srcfile.isfile ()) {srcfile + "파일이 아님");} fileInputStream (srcfile); fileoutputStream (destfile); // 파일이 존재하지 않으면 직접 생성됩니다. 그것이 존재하는 경우, 그것을 삭제하고 byte [] buf = new Byte [8 * 1024]; // int b를 읽고 쓰기; while (b = in.read (buf, 0, buf.length))! = -1) {//read(buf,0,Buf.length) 매개 변수가있는 읽기는 바이트의 총 길이를 반환합니다. 모두 읽을 때 -1; out.write (buf, 0, b); out.flush (); // in.close (); out.close ();}/*** 파일을 복사하고 버퍼링 된 바이트 스트림* @param srcfile* @param destfile* @throws ioexception*/public static void copyfilebuffer (파일 srcfile, destfile)를 추가하는 것이 가장 좋습니다. ioexception {ioexception {if (! srcfile.exists ()) {새로운 불법 불법 행위 렉스크 ( "파일 :"+srcfile+"존재하지 않음");} if (! srcfile.isfile ()) {새로운 불법 불법+"파일이 아님") {new} buffered gresdinputedinputedinputedinputedinputedinputedinputedinputedinputedin fileInputStream (srcfile)); bufferedOutputStream bos = new bufferedOutputStream (new FileoutPutStream (destFile)); int c; while ((c = bis.read ())! = -1) {bos.write (c); bos.flush (); // bufler} bis.close (); bos.close (); 파일 카피에 대한 버퍼링없이* @param srcfile* @param destfile* @throws ioexception*/public static void copyfilebyte (파일 srcfile, 파일 destfile)는 ioexception을 던졌습니다. ioexception {if (! srcfile.exists (! srcfile.exists ESTE ");} if (! srcfile.isfile ()) {새로운 불법 불법 행위 렉스크 (srcfile+"파일이 아님);} fileInputStream in = new FileInputStream (srcfile); fileoutputStream out = new FileOutputStream (destFile); int C; 매개 변수는 읽기 바이트 컨텐츠를 반환합니다. 모든 읽기가 모두 반환되면 -1입니다. out.write (c); out.flush ();} in.close (); out.close (); out.close ();}} 테스트 클래스 :
package com.study.io; import java.io.file; import java.io.ioexception; import org.junit.test; public class ioutiltest {@testpublic void testprinthex () {ioutil.printhex ( "d : //javaio//fileutils.java"); {e.printstacktrace ();}}@testpublic void testprinthexbybytearray () {try {long start = system.currenttimeMillis (); // 1970 년 1 월 1 일 현재 시간과 자정의 시차 (밀리 초로 측정) //ioutil.printhexbybytearray("e://javaio//fileutils.java") ;//ioutil.printhex("e://javaio//1.mp3");ioutil.printhexbybytearray("e://javaio//1.mp3">); end = system.currenttimeMillis (); System.out.println (END -Start);} catch (ioException e) {e.printStackTrace ();}}@testPublic void testCopyFile () {try {ioutil.copyfile ( "새 파일 ("d : //javaio//1.txt "). 파일 ( "d : //javaio//1copy.txt");} catch (ioexception e) {e.printstacktrace ();}}}@testpublic void testcopyfilebybuffer () {long start = system.currenttimemillis ();/*ioutil.copyfilebyte 파일 ( "e : //javaio//1.mp3"), 새 파일 ( "e : //javaio//2.mp3");*////////////// 새 파일 ( "e : //javaio//1.mp3"), new 파일 ( "e : //javaio//3.mp3"); // 10,000 밀리 초 이상*/ioutil.copyfile (새 파일 ( "e : //javaio//1.mp3"), 새 파일 ( "e : //javaio/4.mp3"); // 7mms long end = system.current. 시작);} catch (ioexception e) {e.printstacktrace ();}}} 5. 캐릭터 스트림
package com.study.io; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStreamReader; import java.io.outputStreamwriter; public class israndoswdemo {public void main (] argeceplement {argexemence fileInputStream ( "e : //javaio//utf8.txt"); inputStreamReader ISR = new InputStreamReader (in, "UTF-8"); // 기본 프로젝트 인코딩. 작동 할 때는 파일 자체의 인코딩 형식을 작성해야합니다. fileoutputStream out = new FileOutputStream ( "e : //javaio//utf81.txt"); outputStreamWriter OSW = new OutputStreamWriter (out, "utf-8");/*int c; char [8*1024]; int c;/*배치 읽기, 버퍼 문자 배열을 넣고 0 번째 위치에서 시작한 다음 버퍼를 놓습니다. 반환 된 문자의 수는 읽기 문자 수*/while ((c = isr.read (buffer, 0, buffer.length))! = -1) {string s = new String (buffer, 0, c); system.out.print (s); osw.write (buffer, 0, c); osw.flush ();} isr.close (); osw.close (); osw.close ();}}문자 스트림의 스트림 읽기 및 쓰기 (Filereader/FileWriter)
문자 스트림 용 필터
6. 물체의 직렬화 및 사막화
예:
알아채다: