> Java > java지도 시간 > 본문

파일 디렉토리 읽기, 쓰기 및 삭제의 Java 구현에 대한 자세한 소개

黄舟
풀어 주다: 2017-09-15 10:07:03
원래의
1430명이 탐색했습니다.

이 글에서는 자바 파일 읽기, 쓰기, 삭제 작업의 상세한 구현 코드를 주로 소개합니다. 필요하신 분들은 참고하시면 됩니다.

1. 콘솔 사용자가 입력한 정보를 받아


public String getInputMessage() throws IOException...{
         System.out.println("请输入您的命令∶");
         byte buffer[]=new byte[1024];
         int count=System.in.read(buffer);
         char[] ch=new char[count-2];//最后两位为结束符,删去不要
         for(int i=0;i<count-2;i++)
             ch[i]=(char)buffer[i];
         String str=new String(ch);
         return str;
     }
로그인 후 복사

로 리턴할 수 있습니다. 사용자가 입력하는 정보 중 유일한 단점은 중국어 입력을 지원하지 않으며 추가 개선이 필요하다는 것입니다.

2. 파일 복사

1. 파일 스트림에서 파일 복사


 public void copyFile(String src,String dest) throws IOException...{
         FileInputStream in=new FileInputStream(src);
         File file=new File(dest);
         if(!file.exists())
             file.createNewFile();
         FileOutputStream out=new FileOutputStream(file);
         int c;
         byte buffer[]=new byte[1024];
         while((c=in.read(buffer))!=-1)...{
             for(int i=0;i<c;i++)
                 out.write(buffer[i]);        
         }
         in.close();
         out.close();
     }
로그인 후 복사

이 방법은 테스트되었으며 중국어 처리를 지원하며 txt, xml, jpg, doc, 등 다양한 형식

3. 파일 쓰기

1. PrintStream을 사용하여 파일 쓰기


public void PrintStreamDemo()...{
         try ...{
             FileOutputStream out=new FileOutputStream("D:/test.txt");
             PrintStream p=new PrintStream(out);
             for(int i=0;i<10;i++)
                 p.println("This is "+i+" line");
         } catch (FileNotFoundException e) ...{
             e.printStackTrace();
         }
     }
로그인 후 복사

2. StringBuffer를 사용하여 파일 쓰기


public void StringBufferDemo() throws IOException......{
         File file=new File("/root/sms.log");
         if(!file.exists())
             file.createNewFile();
         FileOutputStream out=new FileOutputStream(file,true);        
         for(int i=0;i<10000;i++)......{
             StringBuffer sb=new StringBuffer();
             sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");
             out.write(sb.toString().getBytes("utf-8"));
         }        
         out.close();
     }
로그인 후 복사

이 방법을 사용하면 사용할 인코딩을 설정할 수 있습니다. 중국 문제를 해결해 보세요.

4. 파일 이름 바꾸기


public void renameFile(String path,String oldname,String newname)...{
         if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名
             File oldfile=new File(path+"/"+oldname);
             File newfile=new File(path+"/"+newname);
             if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
                 System.out.println(newname+"已经存在!");
             else...{
                 oldfile.renameTo(newfile);
             }
         }         
     }
로그인 후 복사

5. 파일 디렉터리 전송

파일을 복사하는 것은 파일을 복사한 후 두 디렉터리에 모두 존재한다는 의미입니다. 파일 디렉터리 전송 전송 후 파일은 새 디렉터리에만 존재하게 됩니다.


public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{
         if(!oldpath.equals(newpath))...{
             File oldfile=new File(oldpath+"/"+filename);
             File newfile=new File(newpath+"/"+filename);
             if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件
                 if(cover)//覆盖
                     oldfile.renameTo(newfile);
                 else
                     System.out.println("在新目录下已经存在:"+filename);
             }
             else...{
                 oldfile.renameTo(newfile);
             }
         }       
     }
로그인 후 복사

6. 파일 읽기

1. FileInputStream을 사용하여 파일 읽기


public String FileInputStreamDemo(String path) throws IOException...{
         File file=new File(path);
         if(!file.exists()||file.isDirectory())
             throw new FileNotFoundException();
         FileInputStream fis=new FileInputStream(file);
         byte[] buf = new byte[1024];
         StringBuffer sb=new StringBuffer();
         while((fis.read(buf))!=-1)...{
             sb.append(new String(buf));    
             buf=new byte[1024];//重新生成,避免和上次读取的数据重复
         }
         return sb.toString();
     }
로그인 후 복사

2 읽기에는 BufferedReader를 사용하세요
IO 작업에서는 BufferedReader 및 BufferedWriter

를 사용하는 것이 더 효율적입니다.


public String BufferedReaderDemo(String path) throws IOException...{
         File file=new File(path);
         if(!file.exists()||file.isDirectory())
             throw new FileNotFoundException();
         BufferedReader br=new BufferedReader(new FileReader(file));
         String temp=null;
         StringBuffer sb=new StringBuffer();
         temp=br.readLine();
         while(temp!=null)...{
             sb.append(temp+" ");
             temp=br.readLine();
         }
         return sb.toString();
     }
로그인 후 복사

3. dom4j를 사용하여 xml 파일 읽기


public Document readXml(String path) throws DocumentException, IOException...{
         File file=new File(path);
         BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
         SAXReader saxreader = new SAXReader();
         Document document = (Document)saxreader.read(bufferedreader);
         bufferedreader.close();
         return document;
     }
로그인 후 복사

Seven. 파일(폴더) 만들기

1. 폴더 만들기


public void createDir(String path)...{
         File dir=new File(path);
         if(!dir.exists())
             dir.mkdir();
     }
로그인 후 복사

rreee

8. 파일(디렉토리) 삭제

1. 파일 삭제

public void createFile(String path,String filename) throws IOException...{
         File file=new File(path+"/"+filename);
         if(!file.exists())
             file.createNewFile();
     }
로그인 후 복사

2. 디렉토리 삭제

File 클래스의 delete() 메소드를 사용하여 디렉토리를 삭제하려는 경우 다음 사항을 확인해야 합니다. 디렉터리에 파일이나 자막이 없으면 삭제가 실패합니다. 따라서 실제 응용 프로그램에서 디렉터리를 삭제하려면 재귀를 사용하여 디렉터리 아래의 모든 하위 디렉터리와 파일을 삭제해야 합니다. 예배 규칙서.

rreee

위 내용은 파일 디렉토리 읽기, 쓰기 및 삭제의 Java 구현에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!