Java read write file creation folder examples of a variety of methods

  • 2020-04-01 02:31:56
  • OfStack

Please modify the garbled code as

BufferedReader br = new BufferedReader(new InputStreamReader)
New FileInputStream (path), "GBK"));

Get the information entered by the console user


public String getInputMessage() throws IOException...{
    System.out.println(" Please enter your command: ");
    byte buffer[]=new byte[1024];
    int count=System.in.read(buffer);
    char[] ch=new char[count-2];//The last two characters are terminators, delete do not
    for(int i=0;i<count-2;i++)
        ch[i]=(char)buffer[i];
    String str=new String(ch);
    return str;
}

Can return the user input information, the disadvantage is that Chinese input is not supported, to be further improved.

Copy files

1. Copy files as a file stream


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();
}

This method has been tested, supports Chinese processing, and can copy a variety of types, such as TXT, XML, JPG, doc and other formats

Write documents

1. Write with 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. Write using 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(" This is the first "+i+" line : None of the methods described above work , Why is it always a strange question  ");
             out.write(sb.toString().getBytes("utf-8"));
         }        
         out.close();
     }

This method can set which code to use and effectively solve Chinese problems.

File renaming


public void renameFile(String path,String oldname,String newname)...{
    if(!oldname.equals(newname))...{//Renaming is necessary when the new file name is different from the previous file name
        File oldfile=new File(path+"/"+oldname);
        File newfile=new File(path+"/"+newname);
        if(newfile.exists())//Renaming is not allowed if there is already a file in the directory that is the same as the new file name
            System.out.println(newname+" Already there! ");
        else...{
            oldfile.renameTo(newfile);
        }
    }         
}

Five. Transfer file directory

The transfer file directory is not the same as the copy file, the copy file is copied after the two directories exist in the file, and the transfer file directory is after the transfer, only the new directory exists in the file.


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 in the directory to be transferred, the file to be transferred already exists
            if(cover)//cover
                oldfile.renameTo(newfile);
            else
                System.out.println(" Already exists under the new directory: "+filename);
        }
        else...{
            oldfile.renameTo(newfile);
        }
    }       
}

Read the document

1. Read files with a 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];//Rebuild to avoid duplication with the last read
         }
         return sb.toString();
     }

2. Use BufferedReader

In IO operations, using BufferedReader and BufferedWriter is a bit more efficient


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. Read the XML file using dom4j


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;
}

7. Create files (folders)

1. Create a folder  


public void createDir(String path){
         File dir=new File(path);
         if(!dir.exists())
             dir.mkdir();
     }  

2. Create a new file


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

Delete files (directories)

1. Delete the file      


public void delFile(String path,String filename){
         File file=new File(path+"/"+filename);
         if(file.exists()&&file.isFile())
             file.delete();
     }

2. Delete the directory

To delete a directory using the delete() method of the File class, we must ensure that there are no files or subdirectories in the directory, otherwise the deletion fails, so in practice, to delete a directory, we must recursively delete all subdirectories and files in the directory, and then delete the directory.


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();
    }
}


Related articles: