People should not be bound by language, our most important is the thought. And thought is absolutely above language.
Preface:
The Language Comparison Manual is a series I’ve always wanted to write: after careful consideration, I’ve decided to do both vertically and horizontally
Compare Java, Kotlin, Javascript, C++, Python, Dart. The vertical version is divided according to knowledge points, and the total number of articles is uncertain. The horizontal version is divided according to language, with a total of 6 articles. Among them:
Java based on jdk8 Kotlin based on jdk8 JavaScript based on node11.10.1 ES6+ C++ based on C++14 Python based on Python 3.7.2 Dart based on Dart2.1.0Copy the code
File manipulation is a required module for every programming language, and this article will take a look at how six languages manipulate files
One, the Java version
1. Create folders:G: / Out/language/Java/dragon. TXT
/** * create File ** @param path File path */ private static void mkFile(String path) {File File = new File(path); If (file.exists()) {//2. Check whether the file has a return; } File parent = file.getParentFile(); //3. Obtain the parent file if (! parent.exists()) { if (! Parent-.mkdirs ()) {//4. Create parent file return; } } try { file.createNewFile(); } catch (IOException e) {e.printStackTrace(); }} | - using String path = "G: / Out/language/Java/dragon. TXT". mkFile(path);Copy the code
2. Write to the character file
/ / private static void writeStr(String path, String path, String path) String content) { File file = new File(path); FileWriter fw = null; try { fw = new FileWriter(file); // Create a character output stream fw.write(content); } catch (IOException e) {e.printStackTrace(); } finally { try { if (fw ! = null) { fw.close(); }} catch (IOException e1) {e1.printStackTrace(); }}} | - using String path = "G: / Out/language/Java/dragon. TXT". String Content = "ying long ---- Zhang Feng Jiete fierce \n" +" a small pool for two years, but wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; writeStr(path, content);Copy the code
3. Write to the character file and specify the character set
/** * Write the code using the character encoding * @param Path path * @param Content content * @param Encoding */ private static void writeStrEncode(String) path, String content, String encoding) { OutputStreamWriter osw = null; try { FileOutputStream fos = new FileOutputStream(path); osw = new OutputStreamWriter(fos, encoding); osw.write(content); } catch (IOException e) { e.printStackTrace(); } finally { try { if (osw ! = null) { osw.close(); } } catch (IOException e) { e.printStackTrace(); }}} | - using String pathGBK = "G: / Out/language/Java/should be dragon - GBK. TXT". String pathUTF8 = "G:/Out/language/ Java/ying-long-utf8.txt "; mkFile(path); String Content = "ying long ---- Zhang Feng Jiete fierce \n" +" a small pool for two years, but wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; writeStrEncode(pathGBK, content, "GBK"); writeStrEncode(pathUTF8, content, "UTF-8");Copy the code
4. Read the character file and define the character set
/** * Read character files * @param path path * @param Encoding format * @return Character content */ Private static String readStrEncode(String) path, String encoding) { InputStreamReader isr = null; try { FileInputStream fis = new FileInputStream(path); isr = new InputStreamReader(fis, encoding); StringBuilder sb = new StringBuilder(); int len = 0; char[] buf = new char[1024]; while ((len = isr.read(buf)) ! = -1) { sb.append(new String(buf, 0, len)); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (isr ! = null) { isr.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } | - using String result = readStrEncode (pathUTF8, "utf-8"); //String result = readStrEncode(pathUTF8, "GBK"); System.out.println(result);Copy the code
5. File operations
| - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / * * * * @ scan folder param dir folder * / private static void scan(String dir) { File fileDir = new File(dir); File[] files = fileDir.listFiles(); for (File file : files) { System.out.println(file.getAbsolutePath()); if (file.isDirectory()) { scan(file.getAbsolutePath()); }}} | - rename -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a String path = "G: / Out/language/Java/dragon. TXT". File file = new File(path); File dest = new File(file.getparent (), "ninglong-temp.txt "); file.renameTo(dest); | - access to disk space -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- long space = dest. GetUsableSpace (); System.out.println(space * 1.f / 1024/1024/1024 + "G"); // 260.25247g long freeSpace = dest.getFreespace (); Println (freeSpace * 1.f / 1024/1024/1024 + "G"); // See system.out.println (freeSpace * 1.f / 1024/1024/1024 + "G"); // 260.2524g long totalSpace = dest. GetTotalSpace (); Println (totalSpace * 1.f / 1024/1024/1024 + "G"); / / 316.00098 G | - modification date -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- String time = new SimpleDateFormat("yyyy/MM/dd a hh:mm:ss ") .format(dest.lastModified()); System.out.println(time); | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- dest. The delete (); // Delete the fileCopy the code
6. Read and write permissions
| - write the related File fileUTF8 = new File (pathUTF8); fileUTF8.setWritable(false); // fileUTF8. SetWritable (true); / / readable fileUTF8 canWrite (); / / whether can write - false | - related fileUTF8 canRead (); Fileutf8.setreadable (false); Fileutf8.setreadable (true); fileutf8.setreadable (true); / / readable fileUTF8 setReadOnly (); / / read-onlyCopy the code
Second, the Kotlin version
1. Create a file
/** * @param path File path */ private fun mkFile(path: String) {val file = file (path)//1 If (file.exists()) {//2. Check whether the file exists. Return} val parent = file.parentfile //3. Get the parent file if (! parent.exists()) { if (! Return}} try {file.createnewFile ()//5. Create a file} the catch (e: IOException) {e.p rintStackTrace ()}} | - using val path = "G: / Out/language/kotlin/should be a dragon. TXT" mkFile (path)Copy the code
2. Write to the character file
It’s cool. Simple and clear. You can also use the Java API
Val content = "ying long ---- Zhang Feng Jiete strong \n" +" a small pool for two years, but wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; val file = File(path) file.writeText(content)Copy the code
3. Write to the character file and specify the character set
By default, Charset has only these, but take a look at the source code to create a Charset using charset.forname
// String content = "ying long ---- Zhang Feng jiete lili \n" +" a small pool for two years, wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; Val pathGBK = "G:/Out/language/kotlin/ yinglong-gbk.txt "val pathUTF8 = "G:/Out/language/kotlin/ yinglong-utf8.txt" val GBK = // Create Charset File(pathGBK).writetext (content, GBK) File(pathUTF8).writetext (content, GBK). Charsets.UTF_8)Copy the code
4. Read the character file and define the character set
Feel pretty cool, all kinds of fancy play
| -- -- -- -- -- - a read val pathUTF8 = "G: / Out/language/kotlin/should be dragon - UTF8. TXT" val result = File (pathUTF8). ReadText (Charsets. UTF_8) / / val result = File (pathUTF8) readText (Charset. Class.forname (" GBK ")) println (result) / / | -- -- -- -- -- -- -- -- according to the line read The File (pathUTF8). ForEachLine {println (it)} / / | -- -- -- -- -- -- -- -- read a few lines of the File (pathUTF8). ReadLines () take (2) the forEach {println (it)} / / | -- -- -- -- -- - the File directly to a variety of open flow, Note their types val fileUTF8 = File(pathUTF8) val isr = Fileutf8.reader (charsets.utF_8)//InputStreamReader Val osw = fileUTF8.writer(Charsets.UTF_8)//OutputStreamWriter val fis = fileUTF8.inputStream()//FileInputStream val fos = fileUTF8.outputStream()//FileOutputStream val br = fileUTF8.bufferedReader(Charsets.UTF_8)//BufferedReader val bw = fileUTF8.bufferedWriter(Charsets.UTF_8)//BufferedWriter val pw = fileUTF8.printWriter(Charsets.UTF_8)//PrintWriterCopy the code
5. File operations
| - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - val dir = "G: / Out/language"; File(dir).walk().maxdepth (2).filter {it.absolutepath.contains ("kotlin")} Println (it. AbsolutePath) / /} | - rename operation -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- val file = file (path) val dest = File(file.parent, "Should the dragon - temp. TXT") file. RenameTo (dest) | - access to disk space -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- val space = Println ((space * 1f / 1024f / 1024f / 1024f).toString() + "G")//260.25247G val freeSpace = Println ((freeSpace * 1f / 1024f / 1024f / 1024f).tostring () + "G")//260.25247G val totalSpace = Dest. TotalSpace / / to get the total disk size println ((totalSpace * 1 f / 1024 f / 1024 f / 1024 f). The toString () + "G") / / G | - 316.00098 Modification date -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- val time = SimpleDateFormat (" yyyy/MM/dd a hh: MM: ss ") Println format (dest. LastModified ()) (time) | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- dest. The delete (); // Delete the fileCopy the code
6. Read and write permissions
| - write related val fileUTF8 = File (pathUTF8) fileUTF8. SetWritable (false). / / not write fileUTF8 setWritable (true) / / to read FileUTF8. CanWrite () / / whether can write - false | - related fileUTF8 canRead (); Fileutf8.setreadable (false); Fileutf8.setreadable (true); fileutf8.setreadable (true); / / readable fileUTF8 setReadOnly (); / / read-onlyCopy the code
Third, JavaScript version
1. Create a file
Create the folder | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | - {recursive: true} said can create recursive const fs = the require (" fs "); let path = "G:/Out/language/javascript"; fs.mkdir(path, {recursive: true}, function (err) { if (err) { console.log(err); } console.log(" create ok"); }); | - create a file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the fs. The writeFile (path + "/ dragon. TXT", "", (err) = > {the if (err) throw err; Console. log(' file created '); });Copy the code
2. Write to the character file
Asynchronous synchronization of writeFile
Ying long ---- Zhang Feng jiete fierce \n" + "a small pool for two years, but wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; | - an asynchronous write fs. WriteFile (path + "/ dragon. TXT", the content, (err) = > {the if (err) throw err; Console. log(' file saved '); }) | - synchronous write fs. WriteFileSync (path + "/ dragon. TXT", "writeFileSync");Copy the code
3. Write to the character file and specify the character set
Default node does not support GBK… , you can use the third-party module ICONV-Lite to convert codes
// String content = "ying long ---- Zhang Feng jiete lili \n" +" a small pool for two years, wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; Fs. writeFile(path + "/ ying-long-utf8.txt ", content, {encoding: 'UTF8 '}, (err) => {if (err) throw err; Console. log(' file saved '); });Copy the code
4. Read the character file and define the character set
| - asynchronous read fs. ReadFile (path + "/ dragon. TXT", (err, data) = > {the if (err) throw err; console.log(data.toString()); }); | - synchronous read let data = fs. ReadFileSync (path + "/ dragon. TXT"). The toString (); console.log(data); | - the open method + read (file descriptor, Buffer, Buffer offset, in bytes, starting position, the callback function) + close let buf = new Buffer. The alloc (1024); Fs. open(pathDir +"/yong-long-temp. TXT ", "r+", (err, fd) => {if (err) throw err; fs.read(fd, buf, 0, buf.length, 0, (err, bytes, buffer) => { console.log(bytes); Console.log (buffer.toString()); // Byte length console.log(buffer.tostring ()); Close (fd, function (err) {// Close the file if (err) throw err; Console. log(" File closed successfully "); }); })});Copy the code
5. File operations
| - file status - asynchronous -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the fs. Stat (path + "/ dragon. TXT", function (err, stats) { if (err) { return console.error(err); } console.log(stats); //Stats { // dev: 3540543445, // mode: 33206, // nlink: 1, // uid: 0, // gid: 0, // rdev: 0, // blksize: Undefined, // ino: 1688849860264802, // size: 123, // blocks: undefined, // atimeMs: 1551622765220.3064, // mtimeMs: undefined, // ino: 1688849860264802, // size: 123, // blocks: undefined, // atimeMs: 1551622765220.3064, // mtimeMs: // birthtimeMs: 1551624397905.7507, // birthtimeMs: 1551622765220.3064, // atime: // birthtime: 2019-03-03-t14:46:37.906z, // birthtime: The T14:2019-03-03 and. 220 z}}); | - file status - synchronous -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- let the stat = fs. StatSync (path + "/ dragon. TXT"); console.log(stat); | - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the fileList (" G: / Out/language ", the file = > {the console. The log (file); }); Function fileList(filePath, CBK) {fs.readdir(filePath, (err,)); Files) => {// read the current folder if (err) throw err; File.foreach (filename => {let file = path.join(filePath, filename); Stat (file, function (eror, stats) {// Get the fs. stats object if (err) throw err; let isFile = stats.isFile(); Let isDir = stats.isdirectory (); If (isFile) {CBK (file); } if (isDir) { fileList(file,cbk); // Recursion, if it is a folder, continue to iterate through the files under that folder}})}); })} | - rename -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the fs. Rename (' G: / Out/language/javascript/dragon. TXT ', 'G: / Out/language/javascript/should be dragon - temp. TXT', (err) = > {the if (err) throw err; Console. log(' rename complete '); }); | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the fs. Unlink (' G: / Out/language/javascript/should be dragon - temp. TXT ', (err) => { if (err) throw err; Console. log(' deletion completed '); });Copy the code
6. Read and write permissions
The options parameter flag field controls read and write permissions
There are many methods, not one said, relatively unfamiliar, or look at the API when you need, or very necessary
'a' - Opens the file for append. If the file does not exist, it is created. 'ax' - is similar to 'a', but fails if the path exists. 'a+' - Opens the file for reading and appending. If the file does not exist, it is created. 'ax+' - is similar to 'a+', but fails if the path exists. 'as' - Opens the file in synchronous mode for append. If the file does not exist, it is created. 'as+' - Opens the file in synchronous mode for reading and appending. If the file does not exist, it is created. 'r' - Opens the file for reading. If the file does not exist, an exception occurs. 'r+' - Opens the file for reading and writing. If the file does not exist, an exception occurs. 'rs' - Reads files synchronously. 'rs+' - Opens the file in synchronous mode for reading and writing. Instructs the operating system to bypass the local file system cache. 'w' - Opens the file for writing. Create the file if it does not exist, and truncate it if it does. 'wx' - Is similar to 'w', but fails if the path exists. 'w+' - Opens the file for reading and writing. Create the file if it does not exist, and truncate it if it does. 'wx+' - is similar to 'w+', but fails if the path exists.Copy the code
Fourth, c + + version
1. Create file:
Create the folder | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # include < direct. H > / create multi-level directory * * * * @ param pDirPath * @ return * / folder path int mkDirs(char *pDirPath) { int i = 0; int iRet; int iLen; char *pszDir; if (nullptr == pDirPath) { return 0; } pszDir = strdup(pDirPath); iLen = static_cast<int>(strlen(pszDir)); For (I = 0; i < iLen; i++) { if (pszDir[i] == '\\' || pszDir[i] == '/') { pszDir[i] = '\0'; iRet = _access(pszDir, 0); // Create if (iRet! = 0) { iRet = _mkdir(pszDir); if (iRet ! = 0) { return -1; } } pszDir[i] = '/'; } } iRet = _mkdir(pszDir); free(pszDir); return iRet; } | - create a file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # include < fstream > ofstream file (" G: / Out/language/c + + / dragon. TXT ");Copy the code
2. Write to the character file
Char *content = "ying long ---- Zhang Feng jiejiejiejiezhi n a pool for two years, but the world a few dust. \n when the thunder wind will rain, should take fuyao into the cloud." ; ofstream file("G:/Out/language/c++/dragon.txt"); if (file.is_open()) { file << content; file.close(); }Copy the code
3. Write to the character file and specify the character set
At present my knowledge about C++ is limited, about the character set related visible: this article: temporarily omitted
4. Read the character file
ifstream file("G:/Out/language/c++/dragon.txt"); char buffer[1024]; while (! file.eof()) { file.getline(buffer, 100); cout << buffer << endl; }Copy the code
5. File operations
The traversal folder section refers to the article
| - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / * * * * @ param traversal folder dir * / void scan (const char * dir) { intptr_t handle; _finddata_t findData; handle = _findfirst(dir, &findData); If (handle == -1) {cout << "Failed to find first file! \n"; return; } do { if (findData.attrib & _A_SUBDIR && ! (strcmp(findData.name, ".") == 0 || strcmp(findData.name, ".." ) == 0)) {// Is a subdirectory and not "." or ".." cout << findData.name << "\t<dir>-----------------------\n"; string subdir(dir); subdir.insert(subdir.find("*"), string(findData.name) + "\\"); cout << subdir << endl; scan(subdir.c_str()); } else {for (int I = 0; i < 4; ++i) cout << "-"; cout << findData.name << "\t" << findData.size << endl; } } while (_findnext(handle, &findData) == 0); // Find the next file in the directory _findclose(handle); / / close the search handle} | - using string inPath = "G: / Out/language / *"; Scan (inpath.c_str ()); // Scan (inpath.c_str ()); | - rename -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a string path = "G: / Out/language/c + + / dragon. TXT". string dest = "G:/Out/language/c++/dragon-temp.txt"; rename(path.c_str(), dest.c_str()); | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the if (! _access(dest.c_str(), 0)) { SetFileAttributes(dest.c_str(), 0); / / / / remove files read-only property if (DeleteFile (dest. The c_str ())) {cout < < dest. C_str () < < "has been successfully deleted." < < endl; } else {cout < < dest. C_str () < < "unable to delete:" < < endl; }} else {cout < < dest. C_str () < < "does not exist, cannot be deleted." < < endl; }Copy the code
6. Read and write permissions
Temporary slightly
Fifth, in Python
1. Create file:
| - create a file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # file created Support multi-level directory file def the create (name) : Parent = os.path.dirname(name) if not os.path.exists(parent): F = open(name, 'w') f.lose () print(name + "created.") else: Print (name + "already existed.") the return | - using filePath = "G: / Out/language/python / 6/7/4/5/6 / dragon. TXT" create (filePath)Copy the code
2. Write to the character file
""" Ying long ---- Zhang Feng jiete strong a small pool for two years, but wash the world a few idle dust. When the thunder wind will rain, should take the fuyao into the cloud." "" f = open(filePath, "w", encoding=" utF-8 ") Overwrite the file if it already exists. If the file does not exist, create a new file. F.lush (content) # f.lush ()Copy the code
3. Write to the character file and specify the character set
FilePathGBK = "G: / Out/language/python / 6/7/4/5/6 / should be dragon - GBK. TXT" content = "" "should be the dragon - packer jet A YouXiaoChi two years, but wash all the dust a few idle. When the thunder wind will rain, should take the fuyao into the cloud." "" f = open(filePathGBK, "w", encoding=" GBK ") f.write(content) # f.flush()Copy the code
4. Read the character file and define the character set
| - as a read f = open (filePath, encoding = "utf-8") # default opened read-only mode: Print (f.readline()) # print(f.readline()) # print(f.readline()) Wash the print is (f.r ead (4)) # earthly world a few spare | - return all rows list f = open (filePath, encoding = "utf-8") # default opened read-only mode: Readlines = f.readlines() #<class 'list'> print(readlines[0]) # ying long ---- print(readlines[1]) # Print (readlines[2]) # | - iteration traversal f = open (filePath, encoding = "utf-8") for the line in iter (f) : # iteration traversal print (line)Copy the code
5. File operations
| - file information -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- f1 = open (filePath) print (f1) fileno ()) # 4 file descriptor print # (f1) mode) R File open mode print(f1.closed) # False Whether file is closed print(f1.encoding) # cp936 File encoding print(f1.name) # G: / Out/language/python / 6/7/4/5/6 / dragon. TXT file name f1. The close () print (OS. Path. The exists (filePath) # True existence Print (os.path.isdir(filePath)) # False if it is a folder print(os.path.isfile(filePath)) # True if it is a file Print (os.path.getsize(filePath)) # 125 print(os.path.basename(filePath)) # # G:/Out/language/python/6/7/4/5/6 print(os.stat(filePath)) #os.stat_result( # st_mode=33206, # st_ino=2533274790397459, # st_dev=3540543445, # st_nlink=1, # st_uid=0, # st_gid=0, # st_size=133, # st_atime=1551668005, # st_mtime=1551668005, # st_ctime = 1551667969) | - file status - synchronous -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- let the stat = fs. StatSync (path + "Should/dragon. TXT"); console.log(stat); | - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # scan files to add all files under the def scan (dir) : if OS. Path. The exists (dir) : lists = os.listdir(dir) for i in range(0,len(lists)): sonPath = os.path.join(dir, lists[i]) print(sonPath) if os.path.isdir(sonPath): Scan (sonPath) | - using scan (" G: / Out/language ") | - rename -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- filePath = "G: / Out/language/python / 6/7/4/5/6 / dragon. TXT" destPath = "G: / Out/language/python / 6/7/4/5/6 / should be dragon - temp. TXT" OS. Rename (filePath, destPath) | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - OS. Remove (destPath)Copy the code
6. Read and write permissions
R: read-only -- the pointer to the file will be placed at the beginning of the file. This is the default mode. # rb: binary read-only. The file pointer will be placed at the beginning of the file. This is the default mode. # r+: read and write. The file pointer will be placed at the beginning of the file. # rb+: binary read and write. The file pointer will be placed at the beginning of the file. # w: Write only -- overwrite the file if it already exists. If the file does not exist, create a new file # WB: binary read-only. Overwrite the file if it already exists. If the file does not exist, create a new file # w+: read-write. Overwrite the file if it already exists. If the file does not exist, create a new file # WB +: binary read/write. Overwrite the file if it already exists. If the file does not exist, create a new file # a: Append. If the file already exists, the file pointer will be placed at the end of the file. The new content will be written after the existing content. If the file does not exist, create a new file for writing. # ab: binary append. # a+: append read and write. # ab+: binary append read and write. Print (os.access(filePath, os.F_OK)) # True Print (os.access(filePath, os.w_ok)) # True print(os.access(filePath, os.x_ok)) # TrueCopy the code
Sixth, the Dart
1. Create a file
| asynchronous create File -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the File (filePath.) the create (recursive: true). Then ((File) {print (" created "); }); | asynchronous create file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void the create (String filePath) async {var file = file (filePath); if (await file.exists()) { return; } await file.create(recursive: true); Print (" create complete "); } | - synchronization to create the File (filePath.) createSync (recursive: true); | - using filePath = "G: / Out/language/python / 6/7/4/5/6 / dragon. TXT"Copy the code
2. Write to the character file
Just to demonstrate the asynchronous, synchronous is simpler, just use it directly
"Ying long ---- Zhang Feng jiete fierce \n" +" a small pool for two years, but wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; File(filePath).writeasString (content).then((File) {print(" write success!") ); });Copy the code
3. Write to the character file and specify the character set
Glancing at the source code, there seems to be no GBK
// String content = "ying long ---- Zhang Feng jiete lili \n" +" a small pool for two years, wash the world a few idle dust. \n" + "When the thunder wind will rain, should take the fuyao into the cloud." ; Val pathISO8859 = "G:/Out/language/kotlin/ iso8859. TXT "File(pathISO8859).writeasString ("Hello Dart", encoding: Encoding.getbyname ("iso_8859-1:1987").then((file) {print(" write successful!").encoding.getByName ("iso_8859-1:1987"). ); });Copy the code
4. Read the character file and define the character set
File(pathGBK)
.readAsString(encoding: Encoding.getByName("iso_8859-1:1987"))
.then((str) {
print(str);
});
Copy the code
5. File operations
| - information about the file. The exists (); // Whether file.length(); // File size (bytes) file.lastmodified (); // Last modified time file.parent-path; / / get the path of the parent folder | - traverse language folders -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - var dir = Directory (r "G: / Out/language"); Var list = dir. List (recursive: true); list.forEach((fs){ print(fs.path); }); | - rename -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var srcPath = R "G: / Out/language/dart / 6/7/4/5/6 / dragon. TXT". Var destPath = r "G: / Out/language/dart / 6/7/4/5/6 / should be dragon - temp. TXT". File(srcPath).rename(destPath); | - delete files -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the File (destPath). The delete ();Copy the code
About each language understanding depth is different, if there is a mistake, welcome to criticize and correct.
Postscript: Jie wen standard
1. Growth record and Errata of this paper
Program source code | The date of | The appendix |
---|---|---|
V0.1, | The 2018-3-4 |
Release name: Programming Language Comparison Manual – Portrait Version [- file -]
Jiwen link: juejin.cn/post/684490…
2. More about me
Pen name | | QQ WeChat | — – | — – | — – | — – | packer fierce | 1981462002 | jet zdl1994328 |
My github: github.com/toly1994328
I’m Jane books: www.jianshu.com/u/e4e52c116… I’m Jane books: www.jianshu.com/u/e4e52c116… Personal website: www.toly1994.com
3. The statement
1—- This article is originally written by Zhang Fengjie, please note if reproduced
2—- welcome the majority of programming enthusiasts to communicate with each other 3—- personal ability is limited, if there is something wrong welcome to criticize and testify, must be humble to correct 4—- see here, I thank you here for your love and support