解決Windows下文件在Linux下打開出現亂碼的問題



問題

前幾天生病了,Java一直在看代碼但是沒跟着打,於是決定偷一波小小的懶,直接把教材的代碼從Windows通過共享文件夾放到了Linux里面。但是編譯的時候出現了問題。

輸入圖片說明

打開文件看,出現亂碼。輸入:set fileencoding?:set fileformat?查看文件編碼和格式

輸入圖片說明

輸入圖片說明

感覺應該是Windows和Linux下文件編碼格式等方面的區別導致的,於是先去網上了解一下具體的原因。

原理

Windows和Linux下文件的區別至少有以下區別:

  • Windows下回車的字符是\r\n,而Linux下是\n
  • Windows下文件的默認編碼方式是GBK2312,Linux下則是UTF-8

解決

本來想直接在Windows里用Notepad++把這些代碼的編碼都改成utf-8,但是這樣一個個點明顯很浪費時間,於是我百度到一些工具,最后選了一個看起來最傻瓜的來試試。在Linux輸入sudo apt-get install enca安裝。然后man一下看看。

enca(1)                                                      

NAME
       enca -- detect and convert encoding of text files

SYNOPSIS
       enca [-L LANGUAGE] [OPTION]... [FILE]...
       enconv [-L LANGUAGE] [OPTION]... [FILE]...

INTRODUCTION AND EXAMPLES
       If you are lucky enough, the only two things you will ever need to know are: command

              enca FILE

       will tell you which encoding file FILE uses (without changing it), and

              enconv FILE

       will  convert file FILE to your locale native encoding.  
       如果你足夠幸運的話,輸入enca 文件名 就可以知道該文件的編碼方式而不改變它。然后輸入enconv 文件名 會自動將該文件轉換成你本地的編碼。

       To convert the file to some other encoding use the -x option (see -x entry in section
       OPTIONS and sections CONVERSION and ENCODINGS for details).使用-x 指定改變后的編碼

       Both work with multiple files and standard input (output) too.  支持批量操作和標准io
       E.g.

              enca -x latin2 <sometext | lpr

       assures file `sometext' is in ISO Latin 2 when it's sent to printer.

       You  can (or have to) use -L option to tell it the right language.  使用-L指定當前語言
       Suppose, you downloaded some Russian HTML file, `file.htm', it claims it's
       windows-1251 but it isn't.  So you run

              enca -L ru file.htm

那還等什么,趕快先試試
先enca查看

輸入圖片說明

再用enconv轉換,打開文件看一眼

輸入圖片說明

成功了,接下來可以批量操作了

輸入圖片說明

總結

Windows下文件格式和Linux下不同,可以使用enca來轉換(也有其他更好的辦法)。主要用法是enca FILE+enconv FILE基本可以直接解決問題,如果沒法自動識別,可以使用enca -L FILE指定當前的編碼,enca -x FILE指定需要轉變成的編碼

參考資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM