Java 읽기 및 쓰기 파일 폴더 작성 방법 예제 상세 정보

부호가 발생했습니다.
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"));
하나.콘솔 사용자가 입력한 정보 얻기

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 등 다양한 형식을 복제할 수 있다
셋.서류를 쓰다
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();
     }
이 방법은 어떤 인코딩을 사용하여 중국어 문제를 효과적으로 해결할 수 있는지 설정할 수 있다.
사.파일 이름 변경

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);
        }
    }      
}
여섯.파일 읽기
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;
}
일곱파일 만들기(폴더)
1. 폴더를 만듭니다

public void createDir(String path){
         File dir=new File(path);
         if(!dir.exists())
             dir.mkdir();
     } 
2. 새 파일 만들기

public void createFile(String path,String filename) throws IOException{
         File file=new File(path+"/"+filename);
         if(!file.exists())
             file.createNewFile();
     }
여덟파일 삭제(디렉토리)
1. 파일 삭제

public void delFile(String path,String filename){
         File file=new File(path+"/"+filename);
         if(file.exists()&&file.isFile())
             file.delete();
     }
2. 디렉터리를 삭제하려면 File 클래스의 delete () 방법을 이용하여 디렉터리를 삭제할 때 이 디렉터리에 파일이나 하위 디렉터리가 없습니다. 그렇지 않으면 삭제에 실패합니다. 따라서 실제 응용 프로그램에서 디렉터리를 삭제하려면 귀속을 이용하여 이 디렉터리에 있는 모든 하위 디렉터리와 문서를 삭제한 다음에 디렉터리를 삭제해야 합니다.

public void delDir(String path)...{
    File dir=new File(path);
    if(dir.exists())...{
        File[] tmp=dir.listFiles();
        for(int i=0;i<tmp.length;i++)...{
            if(tmp[i].isDirectory())...{
                delDir(path+"/"+tmp[i].getName());
            }
            else...{
                tmp[i].delete();
            }
        }
        dir.delete();
    }
}

좋은 웹페이지 즐겨찾기