IO operation is not as frequent as findViewById, so whenever the operation of the file, have to go to Baidu, and then see how others write, and then copy it over, resulting in now encountered IO operation logic, I feel a little nervous, so now sum up
1, the use of File class
File class can achieve File creation, deletion, renaming, access to path modification time, etc. File class constructor passed path, can exist, can not exist, can build out a File object
1.1 Create, delete, move and rename files
File f1=new File("D:\test\xxy.txt");
if(! f1.exists()){// check whether xxy. TXT exists the File object is certain to exist, but the File object pointing to the File File is unknown
try {
f1.createNewFile();// Create a file
} catch (IOException e) {
e.printStackTrace();
}
f1.isDirectory();// Check whether File refers to a directory
f1.isFile();// Check whether the File referred to by this File is a File
f1.delete();// Only directories and files that have no subdirectories or files can be deleted
f1.mkdir();// If the test directory already exists, use this method to create it
f1.mkdirs();// If the test directory does not exist, this method will create test and xxy.txt
}
Copy the code
1.2. Obtain all files in the current directory and obtain common attributes of files
File f2=new File("D:\test");
String[] fileNames=f2.list();You can only view the current directory, not the subdirectories of the subdirectory
System.out.println(Arrays.toString(fileNames));
File[] files=f2.listFiles();// Get File objects for all files in the current directory
for (File file: files) {
file.length();// Get the length of the file
file.getName();// Get the file name
file.getPath();// Get the relative path of the file
file.getAbsolutePath();// Get the absolute path to the file
file.lastModified();// Get the last file modification time
file.isHidden();// Whether the file is hidden
}
// Filter all files in the current directory with suffix TXT,
File[] files1=f2.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt"); }});// Filter all files in the current directory with the suffix TXT, Stream expression
File[] files2=f2.listFiles((file)->file.getName().endsWith(".txt"));
Copy the code
1.3. Specify a directory to search for files
Finds a certain type of file in the specified directory
/ * * * * *@paramTargetFile Specifies the directory *@paramExt is looking for the file suffix */
public static void findFile(File targetFile,String ext){
if(targetFile==null)
return;
if(targetFile.isDirectory()){
File[] files=targetFile.listFiles();
for (File f:
files) {// Recursive call, too many layers easy to OOMfindFile(f,ext); }}else{//file is a file that is not a directory
String name=targetFile.getName();
if(name.endsWith(ext)){ System.out.println(targetFile.getAbsolutePath()); }}}Copy the code
2. Byte input/output streams
IO stream: Input,Output stream (Input,Output) stream is a set of bytes with sequence, starting point and end point. It is the general name and abstraction of data transmission. The data transmission between the two devices called flow is the essence of data transmission, according to data transmission characteristics will flow abstract for various classes, convenient and more intuitive for the classification of the data I/o operation flow According to different types of data are divided into: character stream and byte stream transmitted (eventually will convert byte stream) according to different data flow is divided into: The input stream (which outputs data from a file to a program) and the output stream (which writes data from a program to a file) take the program as a reference
2.1 byte output input stream
Byte OutputStream: OutputStream class definition
public abstract class OutputStream implements Closeable.Flushable
Copy the code
This abstract class is a superclass of all the classes that represent the output byte stream. The output stream receives output bytes and sends them to the InputStream class. A receiver to output to a file uses the FileOutputStream byte InputStream: the InputStream class definition
public abstract class InputStream implements Closeable
Copy the code
This abstract class is the superclass of all classes that are byte input streams FileInputStream takes the input bytes from a file in the file system and outputs them to the file
public static void testOut(a){
//1
File file=new File("D:\test\a.txt");
try {
// create an output stream object
OutputStream fileOutputStream=new FileOutputStream(file,true);//append whether to append output, true does not delete the original content to append, false starts from the beginning
//3, output the content to the file
String info="One,two,three,four,let,s go";
//4, write to the file
fileOutputStream.write(info.getBytes());
// Close the stream
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) { e.printStackTrace(); }}Copy the code
Input content from a file
public static void testIn(a){
//1
File file=new File("D:\test\a.txt");
try {
//2 Build the file input stream object
InputStream fileInoutStream=new FileInputStream(file);
// build the read container
byte[] bytes=new byte[1024];
StringBuilder stringBuilder=new StringBuilder();
int len=-1;// Indicates the length of bytes read each time
// Read reads data into the array and returns the number of bytes read. If the value is not equal to -1, the value is read
while((len=fileInoutStream.read(bytes))! = -1) {//stringBuilder.append(new String(bytes));
stringBuilder.append(new String(bytes,0,len));
}
System.out.println(stringBuilder.toString());
// Close the input stream
fileInoutStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) { e.printStackTrace(); }}Copy the code
The operation principle of input/output streams is that only one byte is read or written from a file at a time. In the process of reading a file, the start position and the read length must be added when the byte array is converted to a string. Otherwise, when the file is read, Output to the string is likely to change much If the cycle number is a not the case you was the length of the file data byte multiples of container when also won’t appear this kind of situation Such as file string length is 5, ‘I’m cold boiled water, for example a total of 10 bytes, the size of your bytes container is 4, cycle to the third time, He fill the two bytes read into the array, the content of the two arrays or after the second loop to read out the content, not clear, so is the content of the read ‘I was cold boiled water in addition to the above problems, there will be a problem, when you container size is odd, or is 1, read out is what the code is a question mark, Since a character is two bytes, when a byte is converted to a string it will be garbled, how do you solve that, when the character input and output stream comes in
3. Character input and output streams
Writer: an abstract class that writes to a character stream and, like OutputStream, operates on a file using the FileWriter character input stream Reader: an abstract class that reads a character stream and instantiates it using the FileReader class to write data to a file
public static void testOut(a){
File file=new File("D:\test\a.txt");
try {
Writer writer=new FileWriter(file,false);// Whether to append
writer.write("I'm cool and white.");
writer.close();
} catch(IOException e) { e.printStackTrace(); }}Copy the code
Read data from a file
public static void testIn(a){
File file=new File("D:\test\a.txt");
try {
Reader reader=new FileReader(file);
char[] cs=new char[1];
int len=-1;
StringBuilder stringBuilder=new StringBuilder();
while((len=reader.read(cs))! = -1){
stringBuilder.append(new String(cs,0,len));
}
System.out.println(stringBuilder);
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) { e.printStackTrace(); }}Copy the code
- The unit of each operation is one character
- The file character operation stream will have its own cache. The default size is 1024 bytes. After the cache is full, or the cache is manually refreshed or the stream is closed, the data will be written to the file
- Character streams are also implemented using byte streams
Byte input/output streams, there’s no caching, files are updated every time they’re written. In all stream operations, bytes are always fundamental, and any bytes-based operation is correct, whether it’s a text file or a binary file. If you are sure that there are printable characters in the stream, consider using the character stream. Due to different encodings, some characters may not be two bytes, may be three bytes, may be one byte, for example, GBK Chinese characters are two bytes, UTF-8 Chinese characters are three bytes, and the character stream is based on the encoding, Convert one or more bytes to Unicode characters in Java, then use stream if the stream is printable, byte stream if not
4, with Java to achieve a simple copy of the file
public class CopyFileDemo {
public static void copy(String srcPath,String targetPath){
File srcFile=new File(srcPath);
File targetFile=new File(targetPath);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream=new FileInputStream(srcFile);
outputStream=new FileOutputStream(targetFile);
byte[] bytes=new byte[1024];
int len=-1;
while((len=inputStream.read(bytes))! = -1){
outputStream.write(bytes,0,len);
}
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(inputStream! =null) inputStream.close();
if(outputStream! =null) outputStream.close();
} catch(IOException e) { e.printStackTrace(); }}}public static void main(String[] args) {
copy("D:\test\aa.jpg"."D:\test\bb\aa.jpg"); }}Copy the code
5. Byte character conversion stream
InputStreamReader: Converts an output stream of characters into an input stream of characters
public static void read(InputStream in){
Reader reader=new InputStreamReader(in,Charset.forName("gbk"));
char[] cs=new char[1024];
int len=-1;
try {
while (true) {if(! ((len=reader.read(cs))! = -1)) break;
System.out.println(new String(cs,0,len));
}
reader.close();
} catch(IOException e) { e.printStackTrace(); }}public static void write(OutputStream out) throws IOException {
Writer write=new OutputStreamWriter(out,Charset.forName("gbk"));
write.write("Cool white open really delicious, a little sweet!");
write.close();
}
public static void main(String[] args) throws IOException {
read(new FileInputStream(new File("D:\test\a.txt")));
write(new FileOutputStream(new File("D:\test\a.txt"))); }Copy the code
6, summary
Byte stream and character stream and byte character conversion stream are still used in the development of quite a lot, respectively introduced their use, or a sentence also have to write more to remember, or forget again! If you can help brothers, one key three even oh!