파일 작동
Java는 종종 파일을 읽고 쓰는 데 사용되므로 일반적으로 사용되는 파일 작업에 대한 요약이 있습니다.
1. 파일을 만듭니다
public static boolean createfile (string filepath) {boolean result = fille = if (! file.exists ()) {rection = file.createnewf iLe (ioxception e); {e.printstacktrace ()}};2. 폴더를 만듭니다
Public Boolean CreateEctory (string directory) {fille = files (! file.exists ()) {recult = reture};3. 파일을 삭제하십시오
public static boolean deletefile (string filepath) {boolean result = fille = if (file.exists ()) {result = fi le.delete (} retud); }4. 폴더를 삭제합니다
폴더 아래에서 하위 파일 및 폴더를 재귀 적으로 삭제합니다
public void deleteDirectory (string filepath) {filepath (! file.exists ()); file.isdirectory () {file.listfiles ();5. 파일을 읽으십시오
(1) 바이트로 파일을 읽습니다. 바이트, 사진, 사운드, 이미지 및 기타 파일과 같은 이진 파일을 읽는 데 종종 사용됩니다.
public static readfilebybytes (string filepath) {file file = if (! file.exists () ||! {byte [] new Byte [1024]; fileInputStream (file); BYTE [1024]; FileInputStream.close} {e.printstacktrace e) {e.printstacktrace ();(2) 문자 단위의 파일을 읽는다. 문자, 숫자 등의 파일을 읽고 중국어 읽기를 지원하는 경우 종종 사용됩니다.
public stath readfilebychars (String filepath) {file file = if (! file.exists () ||! char [] new char [1024]; inputStreamReader = new inputStreamReader (fileInputStrea m, "gbk"); Append (temp). {e .printstacktrace ()} content.toString ();(3) 동작 단위의 파일 읽기 종종 라인 지향 형식 파일을 읽는 데 사용됩니다.
public static list <string> readfilebylines (string filepath) {file file = if (! file.exists () ||! isfile ()) {return null <s tring> content = 새로운 ArrayList <stringStream (FileInputStreamReader); (linecontent.readline ()! = null) {linecontent.out.println (linecontent); } catch (filenotfoundException e) {e.printstacktrace ()} {e.printstacktrace ()};6. 문서를 작성하십시오
문자열이 파일에 쓰여지는 몇 가지 클래스 중에서 Filewriter가 가장 효율적이고 BufferedOutputStream이 있으며 FileoutputStream이 최악입니다.
(1) FileOutputStream을 통해 파일을 작성합니다
public static void writefilebyfileoutputStream (String Filepath, String Content)은 ioexception {file file (filepath) {fi leoutputstream fos = new FileoutputStream (filepath); fos.close ();(2) BufferedOutputStream을 통해 파일을 작성합니다
public static void writefileByBufferedOutStream (String filepath, String Content)은 ioException {filepath (filepath) {bufferedOutputStream = 새로운 bufferedOutputStream (fileoutputStream (filepath); gbk ")); fos.flush (); fos.close ();}}(3) filewriter를 통해 문자열을 작성하십시오
public static void writefilebyfilewriter (String Filepath, String Content)는 ioexception {filepath (filepath) {filewrit er fw = filepath (content); }} 디렉토리 작동
디렉토리는 다른 파일 및 디렉토리를 포함 할 수있는 파일 목록입니다. 디렉토리에 사용 가능한 파일 목록을 나열하려면 파일 개체를 사용하여 디렉토리를 만들어 파일 개체에서 호출 할 수 있고 디렉토리와 관련된 완전하고 자세한 메소드 목록을 얻을 수 있습니다.
디렉토리를 만듭니다
다음은 디렉토리를 만들 수있는 두 가지 유용한 파일 방법입니다.
mkdir () 메소드는 디렉토리를 생성하고 성공을 위해 True를 반환하며 생성 실패에 대해 False를 반환합니다. 실패 상황은 파일 객체의 경로가 이미 존재하거나 전체 경로가 존재하지 않기 때문에 디렉토리를 만들 수 없음을 의미합니다.
mkdirs () 메소드는 디렉토리와 상단 디렉토리를 만듭니다.
다음 예제는 "/tmp/user/java/bin"디렉토리를 만듭니다.
import java.io.file; public class {public static void main (string args []) {string dirname = "/tmp/user/java/bin"; 지금. D.mkdirs ()};위의 코드를 컴파일하고 실행하여 " /tmp /user /java /bin"을 작성하십시오.
팁 : Java는 UNIX 및 Windows 규칙에 따라 경로 분리기를 자동으로 처리합니다. Java의 Windows 버전에서 Forward Slash (/)를 사용하는 경우에도 올바른 경로를 얻을 수 있습니다.
디렉토리 목록
다음과 같이 파일 개체에서 제공 한 List () 메소드를 사용하여 디렉토리에 사용 가능한 모든 파일 및 디렉토리를 나열 할 수 있습니다.
java.io.file; public class readdir {public static void main (string [] args) {file = null [] 경로; // 파일 배열 = 파일. } catch (예외 e) {// 오류가 발생하면 e.printstacktrace ()};/TMP 디렉토리에서 사용 가능한 디렉토리 및 파일을 기반으로 다음 결과가 생성됩니다.
test1.txttest2.txtreaddir.javareaddir.class