Basic operation of java file

Keywords: Java

package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
/**

  • Related operations of documents include
  • File directory create file create file write file read file rename etc
    */
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;

public class FileOperate {
//5. Delete directory
public static void delDir(String path){
File dir=new File(path);
if(dir.exists()){
//The list() method returns the file names of all files and directories in a directory, and the String array
//The listfields () method returns the absolute path of all files and directories in a directory, and the array of files
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();
}
}

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

//7. File rename
public static void renameFile(String path,String oldname,String newname){
    if(!oldname.equals(newname)){//If the new file name is different from the previous one, it is necessary to rename it
        File oldfile=new File(path+"\\"+oldname+".txt");
        File newfile=new File(path+"\\"+newname+".txt");
        if(newfile.exists())//If there is already a file with the same name as the new file in this directory, renaming is not allowed
            System.out.println(newname+"Already exists!");
        else{
            oldfile.renameTo(newfile);
        }
    }         
}


public static void main(String[] args) throws IOException {

//1. Creation of directory
//Define file path
String basepath="D:\FileOperate";

	File dir=new File(basepath);
	
	//Judge if the directory (path) does not exist, create directory (path) dir.mkdir()
	if(!dir.exists()){
		dir.mkdir();
		System.out.println("Folder created successfully!");	
}

//2. Creation of documents

	//Define file name
	String fileName = "firstFile";
	
	//Path the path to the text file you created 
	String path=basepath+"\\"+fileName+".txt";
	
	//Create a directory where files are stored
	File file=new File (path);
	
	//Create file if file does not exist
	if(!file.exists()){
		try {
			file.createNewFile();
		} catch (IOException e) {
			System.out.println(e.getMessage());  
		}
		System.out.println("success create file,the file is"+path);
	}	

//3. File write

	//3.1  FileWriter
	String Data =" This content will append to the end of the file";
	
	try {
		//new FileWriter(file,true); in this way, the existing content and the new content attached to the end of the file will be preserved and will not be overwritten
		FileWriter fileWriter=new FileWriter(path,true);
		
	//\r\n implement line feed
		fileWriter.write(Data+"\r\n Where to play today?\r\n");
		
		//Refresh
		fileWriter.flush();
		
		//close resource
		fileWriter.close();
		
		System.out.println("Done");
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	//3.2.1 BufferedWriter writing files
	String Content="if you don't care,i will kill you";
	try {
		//Create a character buffer stream object
		//BufferedWriter bw=new BufferedWriter(new FileWriter(path)); this will overwrite the previous content
		//In this way, you can append the file content without overwriting it
		
		BufferedWriter BW=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,true)));
		//System.out.println(new FileWriter(path));
		//Write data
		//bw.write(Content);
		
		BW.write(Content);
		//Line feed implementation in BufferedWriter, line feed can also be implemented
		BW.newLine();
		BW.write("weather\r\n");
		BW.write("sunny");
		
		//Refresh after entering data
		BW.flush();
		
		//close resource
		//br.close();
		BW.close();
		System.out.println("OK!");
	//3.2.2 (in IO operation, using BufferedReader and BufferedWriter will be more efficient)
		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();
		}
		String output=sb.toString();
		System.out.println(output);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	//3.3
	//3.3.1FileOutputStream write file
	
	FileOutputStream fop=null;
	
	String content="This is to write a file with a file output stream";
	try {
		
		//Create a FileOutputStream.txt file
		file=new File(basepath+"\\"+"FileOutputStream.txt");
		
		//Create FileInputStream class object FileOutputStream(file,true) and add parameter true, the data added later will not overwrite the previous data
		//FileOutputStream(file); this will overwrite the original data
		fop=new FileOutputStream(file,true);
		
		//If the file does not exist, create the file
		if (!file.exists()) {
		    file.createNewFile();
		   }
		
		//Convert content data to binary data and create byte array
		byte[] contentInBytes=content.getBytes();
		
		//Write array information to a file
		fop.write(contentInBytes);
		
		//Line wrap
		fop.write("\r\n".getBytes());
		
		//Refresh
		fop.flush();
		
		//Closed flow
		fop.close();
		System.out.println("FileOutputStream Done!");
		
		//3.3.2 read file information
		//Create FileInputStream class object
		FileInputStream inputStream=new FileInputStream(file);
		
		//Create byte array
		byte[] readcontent=new byte[1024];
		
		//Read information from file
		int i=inputStream.read(readcontent);
		
		//Information in the output file
		System.out.println(new String(readcontent,0,i));
		
		//Closed flow
		inputStream.close();
		
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}finally{
		try{
			if(fop!=null){
				fop.close();
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}

//4. Catalog deletion
//To delete a directory by using the delete() method of the File class, you must ensure that there are no files or subdirectories in the directory
//Otherwise, the deletion fails, so in practice, we need to delete the directory
//, you must use recursion to delete all subdirectories and files under the directory, and then delete the directory.
//delDir(basepath); delete basepath directory
//delDir(basepath);

//File deletion
//delFile(basepath,"firstFile.txt");

//File rename
//renameFile(basepath, "firstfile", "file");

}

}

Posted by ICEcoffee on Tue, 26 Nov 2019 12:47:13 -0800