To let the code run on every system, use these variables.
1
2
3
4
// depends on the system. On Mac, it is "/"System.out.println(File.separator);
// On Mac, it's ":", used to separate filenames in a sequence of files given as a path listSystem.out.println(File.pathSeparator);
For example, if we want to get a path like “Users/ruoke”, we can create it using
Constructors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 1. Creates a new File instance by converting the given pathname string into an abstract pathname.String filePath ="/Users/ruoke/Documents/java_web/demo-java-spring/src/main/java/com/ruoke/demojavaspring/File/test.txt";
File file1 =new File(filePath);
System.out.println(file1);
// 2. Creates a new File instance from a parent pathname string and a child pathname string.String parent ="/Users/ruoke/Documents/java_web/demo-java-spring/src/main/java/com/ruoke/demojavaspring/File";
String child ="test.txt";
File file2 =new File(parent, child);
System.out.println(file2);
// 3. Creates a new File instance from a parent abstract pathname and a child pathname string.File parent2 =new File(parent);
File file3 =new File(parent2, child);
System.out.println(file3);
Common Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Bytes number. Only applies to files, not directories.System.out.println(fileName.length());
System.out.println(fileName.getAbsolutePath());
// Get a file's or a dir's nameSystem.out.println(fileName.getName());
// Return an absolute path of its parentSystem.out.println(fileName.getParent());
String file_path ="Users/ruoke/test01.txt";
// If this file/dir exists, return false. Else, create it and return trueFile file4 =new File(file_path);
boolean res = file4.createNewFile();
File file5 =new File(file_path);
boolean res = file5.createNewFile();
Byte IO
Byte IO can hanlde all binary files, like pictures, video…
FileOutputStream
Under java.io package, there’s an abstract class OutputStream
Class FileOutputStream extends OutputStream.
If append=false, this constructor will create a file. If this file already exits, the newly created file will replace the older one.
1
2
3
4
5
6
7
8
9
outputStream.write(65);
This will write "A" to the outputfile
String s="abc";
byte[] bytes = s.getBytes();
outputStream.write(bytes);//"abc" outputStream.write(bytes, 1, bytes.length-1);//"bc" outputStream.close();