Preface, for Java itself is a small white, but a little experience in other languages, know that Java is object-oriented, that's all. At the beginning of learning java, I also chewed the first eight chapters of "Java Core Programming Volume", looking as if I understood them all, but closing the book to recall what I had learned seemed to be a blank. ps: I have typed the code on the book, but I feel that this book is still too few examples, lack of that kind of practical problem (just for me, don't spray!). So, I went online to check how other people learn java, the first stop is to know, turned over several posts, saying that this book is the foundation, to carefully gnaw, and then listed a number of key point sets, generics, IO, multi-threading, class loading mechanism, reflection, proxy. Next, I will go online to find the above similar resources, find a small white for me especially suitable online resources, the bottom of the introduction.
Read and write files
There are two ways to read the contents of a file into memory. One is byte type, the other is character type. The details are as follows. In addition, this is a Java IO Tutorial, although English, but very detailed.
read file
// Create file objects File f = new File("/Users/tofu/Downloads/javatext.txt"); // Create File Input Stream FileInputStream fis = new FileInputStream(f); // Create byte arrays byte[] fileContent = new byte[(int)f.length()]; //Read the file contents into the fileContent array fis.read(fileContent); for(byte b:fileContent){ System.out.println(b); } //Close the input stream fis.close();
If the specified file exists, the contents of the file are successfully read into the array in byte format.
Write content to the specified file
Question: Create files in the specified directory. (What if the upper directory of the file does not exist? What about the upper level? )
public void StringToFile(path){ File f = new File(path); //Get the parent directory of the file File dir = f.getParentFile(); //System.out.println(dir); // If the parent directory does not exist, create if (!dir.exists()) { dir.mkdirs(); System.out.println("dir is not exits");} try { // create a file if (!f.exists()) f.createNewFile(); // Create an output stream FileOutputStream fout = new FileOutputStream(f); byte[] tt = {88,89,32,32,43,54,88,89}; //write file fout.write(tt); // Close text output stream fout.close(); }catch(IOException e){ e.printStackTrace(); } }
Folder traversal
As the name implies, it uses java to view files that exist in a directory. There are two situations: files containing subfolders and files without subfolders.
Find out the largest and smallest files (1)
Attention: Does not contain files in subfolders
This is relatively simple, the main thing is that there is a listFiles() function in the File class in Java, and file.length() can calculate the file size, the main code is as follows:
//Create an array of File type, put all the files under the folder into the array, then traverse the array and compare. File dir = new File(path); File[] allFiles = dir.listFilse(); for(File f : allFiles){ if(f.isDirectory()) continue; else{ . } }
Find out the largest and smallest files (2)
Attention: Contains files in subfolders
Seemingly similar problem, in fact, the difficulty is quite different, because the last problem, we only need to list all the files under the designated directory, but this problem is not good, we can not know how many subdirectories there are under the directory, like dialing onions, layer by layer. Here, it is easy to think of using recursion to solve the problem, but this paper does not intend to use recursion method, this paper uses breadth-first search method to solve the problem.
Breadth-first search, in short, is a hierarchical search, the first level of traversal is completed, traversal of the second level. As shown in the figure, the order of traversal is 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8. The main ideas are:
- Create two queues, one for all files counted as q1 and one for all directories counted as q2
- q2 each pop-up a directory, traverse all the files and folders below it, put the files into q1 in order, the directory into q2 in order
- Cycle through the above operations until q2 is empty and the traversal ends
- All documents are stored in q1
- There is no comparison of documents here, because it is relatively simple, we will not talk about it, and paste the code.
public void getAllFiles(){ String path = "/Users/tofu/Downloads"; File root = new File(path); //Store all documents LinkedList<File> fileList = new LinkedList<File>(); //Store all catalogues LinkedList<File> DirList = new LinkedList<File>(); DirList.add(root); long maxLength = Long.MIN_VALUE; long minLength = Long.MAX_VALUE; //Record the current maximum and minimum files File[] fillNames = new File[2]; File queue = null; //Determine whether the directory is empty while(DirList.size()>0){ //Pop up a catalog queue = DirList.remove(); File[] filesInQueue = queue.listFiles(); for (File f:filesInQueue){ if(f.isFile()) { fileList.add(f); long tmpLength = f.length(); if(tmpLength>maxLength){ fillNames[0] = f; maxLength = tmpLength; } if(tmpLength < minLength){ fillNames[1] =f; minLength = tmpLength; } } if(f.isDirectory()) { DirList.add(f); System.out.println(f + "is a Directory"); } } } System.out.println("the maximum file name is" + fillNames[0]+" the size is "+maxLength); System.out.println("the minimum file name is" + fillNames[1]+" the size is "+minLength); }
Split File
Question: Find a file larger than 100k, break it into several sub-files in 100k, and end with the number as the file name.
public void splitFile(String toSplitFile){ File sourceFile = new File(toSplitFile); byte[] fileContent = new byte[(int) sourceFile.length()]; int fileNum = 0; FileInputStream fis=null; try(fis = new FileInputStream(sourceFile)){ fis.read(fileContent); }catch(IOException e){ e.printStackTrace(); } //Store the contents of each small file byte[] eachContent; //Calculate the number of files if(sourceFile.length()%blockSize==0){ fileNum = fileContent.length/blockSize; } else{ fileNum = fileContent.length/blockSize+1; } FileOutputStream fout =null; for(int i=0;i<fileNum;i++){ File f = new File(sourceFile.getParent(),sourceFile.getName()+"_"+i); if (i!=fileNum-1){ eachContent = Arrays.copyOfRange(fileContent,i*blockSize,(i+1)*blockSize); } else{ eachContent = Arrays.copyOfRange(fileContent,i*blockSize,fileContent.length); } try(fout = new FileOutputStream(f)){ fout.write(eachContent); }catch(IOException e){ e.printStackTrace(); } System.out.printf("the no %d is create\n",i); } }
Document merging
Question: Merge the above split files
public void mergeFile(String floder, String name){ File allFiles = new File(floder,name); try(FileOutputStream fout = new FileOutputStream(allFiles)){ int i = 1; while(true){ File f = new File(floder,name+"_"+i++); if(!f.exists()) break; byte[] each = new byte[(int)f.length()]; try(FileInputStream fis =new FileInputStream(f)){ fis.read(each); }catch(IOException e){ e.printStackTrace(); } fout.write(each); } }catch(IOException e){ e.printStackTrace(); } System.out.println("the file is create"); }
Two Closing Modes of Stream
Close in final
-
First, the reference declaration of the flow is outside of try. If the declaration is inside try, its scope of action cannot reach final.
-
Before finally closes, determine if the reference is empty
-
When closed, try catch processing needs to be done again
public static void main(String[] args) { File f = new File("/Users/tofu/Downloads/javaTest.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } finally { // Close the flow in final if (null != fis) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Close in try
File f = new File("d:/lol.txt"); //Defining the flow in try(), try,catch, or finally closes automatically try (FileInputStream fis = new FileInputStream(f)) { byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); }
Website Introduction
I am studying on this website. I feel that the stationmaster is very good, and the examples are very clear. Part of the website is free, part is free, I am still learning free, maybe next time you learn the spring framework, you will buy the fee. It's not advertising here, but thanks to the webmaster for making me gain.