Как определить кодировку файла в windows

👍 Кодировкой текста в файлах цифровых документов называют способ сопоставления последовательностей байт символам языка.

Как определить кодировку текстового файла

Кодировкой текста в файлах цифровых документов называют способ сопоставления последовательностей байт символам языка. Существует множество различных кодировок для разных языков. Определить кодировку текстового файла можно при помощи ряда программных средств.

Как определить кодировку текстового файла

Вам понадобится

  • — Microsoft Office Word;
  • — KWrite;
  • — Mozilla Firefox;
  • — enca.

Инструкция

Используйте редактор Microsoft Office Word, если он установлен на компьютере, для определения кодировки текстового файла. Запустите данное приложение. В главном меню последовательно выберите пункты «Файл» и «Открыть…» или нажмите сочетание клавиш Ctrl+O. В отобразившемся диалоге перейдите к нужному каталогу и выделите файл. Нажмите кнопку «Открыть». Если кодировка текста отличается от CP1251, автоматически откроется диалог «Преобразование файла». Активируйте в нем опцию «Другая» и подберите кодировку, используя список, находящийся справа. При выборе правильной кодировки в поле «Образец» будет выведен читаемый текст.

Примените текстовые редакторы, допускающие выбор кодировки текста источника. Хорошим примером подобного приложения является KWrite (работает в среде KDE в UNIX-подобных системах). Загрузите текстовый файл в редактор. Затем просто перебирайте кодировки, пока не отобразится читаемый текст (в KWrite для этого используется раздел Encoding меню Tools).

Аналогично текстовому редактору для определения кодировки файла можно использовать и браузер. Воспользуйтесь Mozilla Firefox. Запустите данное приложение. Если оно не установлено, загрузите подходящий дистрибутив с сайта mozilla.org и инсталлируйте его. Откройте в браузере текстовый файл. Для этого выберите в главном меню пункты «Файл» и «Открыть файл…» или нажмите Ctrl+O. Если загруженный текст отобразился корректно, разверните раздел «Кодировка» меню «Вид» и узнайте кодировку из названия пункта, на котором установлена отметка. В противном случае подберите данный параметр путем выбора различных пунктов того же меню, а также его раздела «Дополнительные».

Примените специализированные утилиты для определения кодировок текстовых файлов. В UNIX-подобных системах можно использовать enca. При необходимости установите эту программу при помощи доступных менеджеров пакетов. Выведите список доступных языков, выполнив команду:

enca —list languages

Определите кодировку текстового файла, указав его имя при помощи опции -g и язык документа при помощи опции -L. Например:

enca -L russian -g /home/vic/tmp/aaa.txt.

Источники:

  • Кодировка текста ASCII

Войти на сайт

или

Забыли пароль?
Еще не зарегистрированы?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Программный комплекс SocialKit корректно работает с кириллицей в текстовых файлах, кодировка которых соответствует стандарту Windows-1251 (кратко может быть записано как CP1251 или ANSI). В этой связи в задачах, поддерживающих указание внешнего файла с перечнем комментариев, сообщений, описаний и прочей информации, которая может содержать кириллицу, нужно указывать текстовые файлы, где русский текст задан в кодировке по стандарту Windows-1251 или же просто ANSI, или CP1251 — всё это, по сути, одно и то же.

Учитывая, что многие инструменты по работе с текстом не отображают, в какой именно кодировке задан текст в текстовом файле и/или не поддерживают преобразование кодировок, то у новичков часто возникает вопрос о том, как именно привести кодировку текстового файла с русским текстом к понятному для SocialKit формату CP1251.

Следует сразу отметить, что большинство текстовых редакторов для ОС Windows (например, встроенный Блокнот и Wordpad) по умолчанию создают текстовые файлы именно с кодировкой по стандарту Windows-1251. Однако, эта кодировка по умолчанию может быть изменена в следствие тех или иных действий.

Если вы не уверены в том, в какой именно кодировке задан текст, то проще всего этот текст пересохранить через стандартный Блокнот Windows. При пересохранении Блокнот также покажет, в каком формате текст сейчас.

Опишем эту простую процедуру по шагам.

1. Открыть искомый текстовый файл в Блокноте Windows и выбрать пункт меню «Файл» -> «Сохранить как…».

Image 47453

Пример текстового файла, в котором русский текст задан в формате UTF, но это не очевидно при открытии.

2. В открывшемся диалоговом окне вы сразу видите, в какой кодировке был сохранён текст в текстовом файле.

Image 47454

Диалоговое окно пересохранения текстового файла, в котором можно сразу изменить кодировку.

Как видно, в примере текст в текстовом файле был ранее сохранён в кодировке UTF-8. Для изменения кодировке достаточно выбрать в выпадающем списке кодировку ANSI и нажать кнопку «Сохранить«.

При этом зрительно для вас ничего не изменится, но многое изменится для программы и алгоритмов, занимающихся обработкой текста в процессе отправки. Корректно Instagram’у будет отправлен только ANSI-текст.

This isn’t really a programming question, is there a command line or Windows tool (Windows 7) to get the current encoding of a text file? Sure I can write a little C# app but I wanted to know if there is something already built in?

Ross Ridge's user avatar

Ross Ridge

37.8k7 gold badges79 silver badges111 bronze badges

asked Sep 14, 2010 at 15:28

TheWebGuy's user avatar

3

Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click «Save As…«.
It’ll look like this:
enter image description here

Whatever the default-selected encoding is, that is what your current encoding is for the file.

If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).

I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.

FYI: From my understanding I think «Unicode» (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad’s «Unicode» option: Windows 7 — UTF-8 and Unicdoe

Community's user avatar

answered Nov 20, 2012 at 0:27

MikeTeeVee's user avatar

MikeTeeVeeMikeTeeVee

18k7 gold badges76 silver badges70 bronze badges

14

If you have «git» or «Cygwin» on your Windows Machine, then go to the folder where your file is present and execute the command:

file *

This will give you the encoding details of all the files in that folder.

answered Apr 19, 2017 at 7:37

George Ninan's user avatar

George NinanGeorge Ninan

1,9092 gold badges12 silver badges8 bronze badges

4

The (Linux) command-line tool ‘file’ is available on Windows via GnuWin32:

http://gnuwin32.sourceforge.net/packages/file.htm

If you have git installed, it’s located in C:Program Filesgitusrbin.

Example:

    C:UsersSHDownloadsSquareRoot>file *
    _UpgradeReport_Files;         directory
    Debug;                        directory
    duration.h;                   ASCII C++ program text, with CRLF line terminators
    ipch;                         directory
    main.cpp;                     ASCII C program text, with CRLF line terminators
    Precision.txt;                ASCII text, with CRLF line terminators
    Release;                      directory
    Speed.txt;                    ASCII text, with CRLF line terminators
    SquareRoot.sdf;               data
    SquareRoot.sln;               UTF-8 Unicode (with BOM) text, with CRLF line terminators
    SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary info
    SquareRoot.vcproj;            XML  document text
    SquareRoot.vcxproj;           XML document text
    SquareRoot.vcxproj.filters;   XML document text
    SquareRoot.vcxproj.user;      XML document text
    squarerootmethods.h;          ASCII C program text, with CRLF line terminators
    UpgradeLog.XML;               XML  document text

    C:UsersSHDownloadsSquareRoot>file --mime-encoding *
    _UpgradeReport_Files;         binary
    Debug;                        binary
    duration.h;                   us-ascii
    ipch;                         binary
    main.cpp;                     us-ascii
    Precision.txt;                us-ascii
    Release;                      binary
    Speed.txt;                    us-ascii
    SquareRoot.sdf;               binary
    SquareRoot.sln;               utf-8
    SquareRoot.sln.docstates.suo; binary
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary infobinary
    SquareRoot.vcproj;            us-ascii
    SquareRoot.vcxproj;           utf-8
    SquareRoot.vcxproj.filters;   utf-8
    SquareRoot.vcxproj.user;      utf-8
    squarerootmethods.h;          us-ascii
    UpgradeLog.XML;               us-ascii

Ed S.'s user avatar

Ed S.

121k21 gold badges181 silver badges262 bronze badges

answered Jan 13, 2016 at 11:58

Sybren's user avatar

SybrenSybren

8716 silver badges5 bronze badges

7

Install git ( on Windows you have to use git bash console). Type:

file --mime-encoding *   

for all files in the current directory , or

file --mime-encoding */*   

for the files in all subdirectories

Ross Rogers's user avatar

Ross Rogers

23.1k26 gold badges107 silver badges163 bronze badges

answered Nov 15, 2019 at 14:57

phd_coder's user avatar

phd_coderphd_coder

3613 silver badges3 bronze badges

1

Here’s my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii when no BOM is present (like most text editors, the default would be UTF8 if you want to match the HTTP/web ecosystem).

Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.

# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
    $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)

    if(!$bytes) { return 'utf8' }

    switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
        '^efbbbf'   { return 'utf8' }
        '^2b2f76'   { return 'utf7' }
        '^fffe'     { return 'unicode' }
        '^feff'     { return 'bigendianunicode' }
        '^0000feff' { return 'utf32' }
        default     { return 'ascii' }
    }
}

dir ~DocumentsWindowsPowershell -File | 
    select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} | 
    ft -AutoSize

Recommendation: This can work reasonably well if the dir, ls, or Get-ChildItem only checks known text files, and when you’re only looking for «bad encodings» from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)

answered Jan 22, 2015 at 0:02

yzorg's user avatar

yzorgyzorg

4,1163 gold badges39 silver badges56 bronze badges

8

A simple solution might be opening the file in Firefox.

  1. Drag and drop the file into firefox
  2. Press Ctrl+I to open the page info

and the text encoding will appear on the «Page Info» window.

enter image description here

Note: If the file is not in txt format, just rename it to txt and try again.

P.S. For more info see this article.

answered Aug 8, 2019 at 17:37

Just Shadow's user avatar

Just ShadowJust Shadow

10.1k5 gold badges55 silver badges69 bronze badges

1

I wrote the #4 answer (at time of writing). But lately I have git installed on all my computers, so now I use @Sybren’s solution. Here is a new answer that makes that solution handy from powershell (without putting all of git/usr/bin in the PATH, which is too much clutter for me).

Add this to your profile.ps1:

$global:gitbin = 'C:Program FilesGitusrbin'
Set-Alias file.exe $gitbinfile.exe

And used like: file.exe --mime-encoding *. You must include .exe in the command for PS alias to work.

But if you don’t customize your PowerShell profile.ps1 I suggest you start with mine: https://gist.github.com/yzorg/8215221/8e38fd722a3dfc526bbe4668d1f3b08eb7c08be0
and save it to ~DocumentsWindowsPowerShell. It’s safe to use on a computer without git, but will write warnings when git is not found.

The .exe in the command is also how I use C:WINDOWSsystem32where.exe from powershell; and many other OS CLI commands that are «hidden by default» by powershell, *shrug*.

answered Oct 18, 2017 at 17:36

yzorg's user avatar

yzorgyzorg

4,1163 gold badges39 silver badges56 bronze badges

4

you can simply check that by opening your git bash on the file location then running the command file -i file_name

example

user filesData
$ file -i data.csv
data.csv: text/csv; charset=utf-8

answered Feb 23, 2022 at 14:04

DINA TAKLIT's user avatar

DINA TAKLITDINA TAKLIT

5,8829 gold badges61 silver badges72 bronze badges

Some C code here for reliable ascii, bom’s, and utf8 detection: https://unicodebook.readthedocs.io/guess_encoding.html

Only ASCII, UTF-8 and encodings using a BOM (UTF-7 with BOM, UTF-8 with BOM,
UTF-16, and UTF-32) have reliable algorithms to get the encoding of a document.
For all other encodings, you have to trust heuristics based on statistics.

EDIT:

A powershell version of a C# answer from: Effective way to find any file’s Encoding. Only works with signatures (boms).

# get-encoding.ps1
param([Parameter(ValueFromPipeline=$True)] $filename)    
begin {
  # set .net current directoy                                                                                                   
  [Environment]::CurrentDirectory = (pwd).path
}
process {
  $reader = [System.IO.StreamReader]::new($filename, 
    [System.Text.Encoding]::default,$true)
  $peek = $reader.Peek()
  $encoding = $reader.currentencoding
  $reader.close()
  [pscustomobject]@{Name=split-path $filename -leaf
                BodyName=$encoding.BodyName
                EncodingName=$encoding.EncodingName}
}


.get-encoding chinese8.txt

Name         BodyName EncodingName
----         -------- ------------
chinese8.txt utf-8    Unicode (UTF-8)


get-childitem -file | .get-encoding

answered Nov 8, 2018 at 17:43

js2010's user avatar

js2010js2010

21.1k4 gold badges56 silver badges60 bronze badges

1

Looking for a Node.js/npm solution? Try encoding-checker:

npm install -g encoding-checker

Usage

Usage: encoding-checker [-p pattern] [-i encoding] [-v]
 
Options:
  --help                 Show help                                     [boolean]
  --version              Show version number                           [boolean]
  --pattern, -p, -d                                               [default: "*"]
  --ignore-encoding, -i                                            [default: ""]
  --verbose, -v                                                 [default: false]

Examples

Get encoding of all files in current directory:

encoding-checker

Return encoding of all md files in current directory:

encoding-checker -p "*.md"

Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):

encoding-checker -p "**"

For more examples refer to the npm docu or the official repository.

answered Jan 27, 2021 at 21:22

ToJo's user avatar

ToJoToJo

1,2291 gold badge14 silver badges24 bronze badges

0

Similar to the solution listed above with Notepad, you can also open the file in Visual Studio, if you’re using that. In Visual Studio, you can select «File > Advanced Save Options…»

The «Encoding:» combo box will tell you specifically which encoding is currently being used for the file. It has a lot more text encodings listed in there than Notepad does, so it’s useful when dealing with various files from around the world and whatever else.

Just like Notepad, you can also change the encoding from the list of options there, and then saving the file after hitting «OK». You can also select the encoding you want through the «Save with Encoding…» option in the Save As dialog (by clicking the arrow next to the Save button).

answered Oct 11, 2016 at 18:57

JaykeBird's user avatar

JaykeBirdJaykeBird

3756 silver badges16 bronze badges

2

The only way that I have found to do this is VIM or Notepad++.

answered Sep 14, 2017 at 15:49

Todd Partridge's user avatar

Todd PartridgeTodd Partridge

6331 gold badge8 silver badges10 bronze badges

1

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

answered Jul 8, 2020 at 16:29

Amr Ali's user avatar

Amr AliAmr Ali

2,6121 gold badge16 silver badges11 bronze badges

This isn’t really a programming question, is there a command line or Windows tool (Windows 7) to get the current encoding of a text file? Sure I can write a little C# app but I wanted to know if there is something already built in?

Ross Ridge's user avatar

Ross Ridge

37.8k7 gold badges79 silver badges111 bronze badges

asked Sep 14, 2010 at 15:28

TheWebGuy's user avatar

3

Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click «Save As…«.
It’ll look like this:
enter image description here

Whatever the default-selected encoding is, that is what your current encoding is for the file.

If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).

I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.

FYI: From my understanding I think «Unicode» (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad’s «Unicode» option: Windows 7 — UTF-8 and Unicdoe

Community's user avatar

answered Nov 20, 2012 at 0:27

MikeTeeVee's user avatar

MikeTeeVeeMikeTeeVee

18k7 gold badges76 silver badges70 bronze badges

14

If you have «git» or «Cygwin» on your Windows Machine, then go to the folder where your file is present and execute the command:

file *

This will give you the encoding details of all the files in that folder.

answered Apr 19, 2017 at 7:37

George Ninan's user avatar

George NinanGeorge Ninan

1,9092 gold badges12 silver badges8 bronze badges

4

The (Linux) command-line tool ‘file’ is available on Windows via GnuWin32:

http://gnuwin32.sourceforge.net/packages/file.htm

If you have git installed, it’s located in C:Program Filesgitusrbin.

Example:

    C:UsersSHDownloadsSquareRoot>file *
    _UpgradeReport_Files;         directory
    Debug;                        directory
    duration.h;                   ASCII C++ program text, with CRLF line terminators
    ipch;                         directory
    main.cpp;                     ASCII C program text, with CRLF line terminators
    Precision.txt;                ASCII text, with CRLF line terminators
    Release;                      directory
    Speed.txt;                    ASCII text, with CRLF line terminators
    SquareRoot.sdf;               data
    SquareRoot.sln;               UTF-8 Unicode (with BOM) text, with CRLF line terminators
    SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary info
    SquareRoot.vcproj;            XML  document text
    SquareRoot.vcxproj;           XML document text
    SquareRoot.vcxproj.filters;   XML document text
    SquareRoot.vcxproj.user;      XML document text
    squarerootmethods.h;          ASCII C program text, with CRLF line terminators
    UpgradeLog.XML;               XML  document text

    C:UsersSHDownloadsSquareRoot>file --mime-encoding *
    _UpgradeReport_Files;         binary
    Debug;                        binary
    duration.h;                   us-ascii
    ipch;                         binary
    main.cpp;                     us-ascii
    Precision.txt;                us-ascii
    Release;                      binary
    Speed.txt;                    us-ascii
    SquareRoot.sdf;               binary
    SquareRoot.sln;               utf-8
    SquareRoot.sln.docstates.suo; binary
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary infobinary
    SquareRoot.vcproj;            us-ascii
    SquareRoot.vcxproj;           utf-8
    SquareRoot.vcxproj.filters;   utf-8
    SquareRoot.vcxproj.user;      utf-8
    squarerootmethods.h;          us-ascii
    UpgradeLog.XML;               us-ascii

Ed S.'s user avatar

Ed S.

121k21 gold badges181 silver badges262 bronze badges

answered Jan 13, 2016 at 11:58

Sybren's user avatar

SybrenSybren

8716 silver badges5 bronze badges

7

Install git ( on Windows you have to use git bash console). Type:

file --mime-encoding *   

for all files in the current directory , or

file --mime-encoding */*   

for the files in all subdirectories

Ross Rogers's user avatar

Ross Rogers

23.1k26 gold badges107 silver badges163 bronze badges

answered Nov 15, 2019 at 14:57

phd_coder's user avatar

phd_coderphd_coder

3613 silver badges3 bronze badges

1

Here’s my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii when no BOM is present (like most text editors, the default would be UTF8 if you want to match the HTTP/web ecosystem).

Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.

# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
    $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)

    if(!$bytes) { return 'utf8' }

    switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
        '^efbbbf'   { return 'utf8' }
        '^2b2f76'   { return 'utf7' }
        '^fffe'     { return 'unicode' }
        '^feff'     { return 'bigendianunicode' }
        '^0000feff' { return 'utf32' }
        default     { return 'ascii' }
    }
}

dir ~DocumentsWindowsPowershell -File | 
    select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} | 
    ft -AutoSize

Recommendation: This can work reasonably well if the dir, ls, or Get-ChildItem only checks known text files, and when you’re only looking for «bad encodings» from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)

answered Jan 22, 2015 at 0:02

yzorg's user avatar

yzorgyzorg

4,1163 gold badges39 silver badges56 bronze badges

8

A simple solution might be opening the file in Firefox.

  1. Drag and drop the file into firefox
  2. Press Ctrl+I to open the page info

and the text encoding will appear on the «Page Info» window.

enter image description here

Note: If the file is not in txt format, just rename it to txt and try again.

P.S. For more info see this article.

answered Aug 8, 2019 at 17:37

Just Shadow's user avatar

Just ShadowJust Shadow

10.1k5 gold badges55 silver badges69 bronze badges

1

I wrote the #4 answer (at time of writing). But lately I have git installed on all my computers, so now I use @Sybren’s solution. Here is a new answer that makes that solution handy from powershell (without putting all of git/usr/bin in the PATH, which is too much clutter for me).

Add this to your profile.ps1:

$global:gitbin = 'C:Program FilesGitusrbin'
Set-Alias file.exe $gitbinfile.exe

And used like: file.exe --mime-encoding *. You must include .exe in the command for PS alias to work.

But if you don’t customize your PowerShell profile.ps1 I suggest you start with mine: https://gist.github.com/yzorg/8215221/8e38fd722a3dfc526bbe4668d1f3b08eb7c08be0
and save it to ~DocumentsWindowsPowerShell. It’s safe to use on a computer without git, but will write warnings when git is not found.

The .exe in the command is also how I use C:WINDOWSsystem32where.exe from powershell; and many other OS CLI commands that are «hidden by default» by powershell, *shrug*.

answered Oct 18, 2017 at 17:36

yzorg's user avatar

yzorgyzorg

4,1163 gold badges39 silver badges56 bronze badges

4

you can simply check that by opening your git bash on the file location then running the command file -i file_name

example

user filesData
$ file -i data.csv
data.csv: text/csv; charset=utf-8

answered Feb 23, 2022 at 14:04

DINA TAKLIT's user avatar

DINA TAKLITDINA TAKLIT

5,8829 gold badges61 silver badges72 bronze badges

Some C code here for reliable ascii, bom’s, and utf8 detection: https://unicodebook.readthedocs.io/guess_encoding.html

Only ASCII, UTF-8 and encodings using a BOM (UTF-7 with BOM, UTF-8 with BOM,
UTF-16, and UTF-32) have reliable algorithms to get the encoding of a document.
For all other encodings, you have to trust heuristics based on statistics.

EDIT:

A powershell version of a C# answer from: Effective way to find any file’s Encoding. Only works with signatures (boms).

# get-encoding.ps1
param([Parameter(ValueFromPipeline=$True)] $filename)    
begin {
  # set .net current directoy                                                                                                   
  [Environment]::CurrentDirectory = (pwd).path
}
process {
  $reader = [System.IO.StreamReader]::new($filename, 
    [System.Text.Encoding]::default,$true)
  $peek = $reader.Peek()
  $encoding = $reader.currentencoding
  $reader.close()
  [pscustomobject]@{Name=split-path $filename -leaf
                BodyName=$encoding.BodyName
                EncodingName=$encoding.EncodingName}
}


.get-encoding chinese8.txt

Name         BodyName EncodingName
----         -------- ------------
chinese8.txt utf-8    Unicode (UTF-8)


get-childitem -file | .get-encoding

answered Nov 8, 2018 at 17:43

js2010's user avatar

js2010js2010

21.1k4 gold badges56 silver badges60 bronze badges

1

Looking for a Node.js/npm solution? Try encoding-checker:

npm install -g encoding-checker

Usage

Usage: encoding-checker [-p pattern] [-i encoding] [-v]
 
Options:
  --help                 Show help                                     [boolean]
  --version              Show version number                           [boolean]
  --pattern, -p, -d                                               [default: "*"]
  --ignore-encoding, -i                                            [default: ""]
  --verbose, -v                                                 [default: false]

Examples

Get encoding of all files in current directory:

encoding-checker

Return encoding of all md files in current directory:

encoding-checker -p "*.md"

Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):

encoding-checker -p "**"

For more examples refer to the npm docu or the official repository.

answered Jan 27, 2021 at 21:22

ToJo's user avatar

ToJoToJo

1,2291 gold badge14 silver badges24 bronze badges

0

Similar to the solution listed above with Notepad, you can also open the file in Visual Studio, if you’re using that. In Visual Studio, you can select «File > Advanced Save Options…»

The «Encoding:» combo box will tell you specifically which encoding is currently being used for the file. It has a lot more text encodings listed in there than Notepad does, so it’s useful when dealing with various files from around the world and whatever else.

Just like Notepad, you can also change the encoding from the list of options there, and then saving the file after hitting «OK». You can also select the encoding you want through the «Save with Encoding…» option in the Save As dialog (by clicking the arrow next to the Save button).

answered Oct 11, 2016 at 18:57

JaykeBird's user avatar

JaykeBirdJaykeBird

3756 silver badges16 bronze badges

2

The only way that I have found to do this is VIM or Notepad++.

answered Sep 14, 2017 at 15:49

Todd Partridge's user avatar

Todd PartridgeTodd Partridge

6331 gold badge8 silver badges10 bronze badges

1

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

answered Jul 8, 2020 at 16:29

Amr Ali's user avatar

Amr AliAmr Ali

2,6121 gold badge16 silver badges11 bronze badges

0 / 0 / 0

Регистрация: 15.07.2019

Сообщений: 22

1

13.05.2020, 01:25. Показов 3261. Ответов 29


есть файлы

1.txt
2.txt
3.txt
4.txt
5.txt

нужно из батника (cmd) узнать какая кодировка у каждого файла.

возможные варианты кодировок:
(«ansi», «utf8», «unicode»)

идеально получить значение в переменную.

можна юзать стандартные команды виндовс (cmd) и PS

Windows Batch file
1
2
3
4
5
6
FOR /L %%I IN (1,1,5) DO (
ECHO узнать кодировку "%%I.txt"
set /p codePage= КОДИРОВКА < "%%I.txt"
start programm.exe -x 1 -y "%%I.txt" -z %codePage% -OUTPUT
move OUTPUT OUTPUT_%codePage%
)

где-то так…
но понять как можна получить кодировку ДРУГОГО файла а не поточного батника -найти не смог (((

Добавлено через 29 минут
незнаю на чем ЭТО,
но может как-то можна «сварганить» что-то подобное на баш/пш ???

Код

public static class StreamExtension
{
    /// <summary>
    /// Convert the content to a string.
    /// </summary>
    /// <param name="stream">The stream.</param>
    /// <returns></returns>
    public static string ReadAsString(this Stream stream)
    {
        var startPosition = stream.Position;
        try
        {
            // 1. Check for a BOM
            // 2. or try with UTF-8. The most (86.3%) used encoding. Visit: http://w3techs.com/technologies/overview/character_encoding/all/
            var streamReader = new StreamReader(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true);
            return streamReader.ReadToEnd();
        }
        catch (DecoderFallbackException ex)
        {
            stream.Position = startPosition;

            // 3. The second most (6.7%) used encoding is ISO-8859-1. So use Windows-1252 (0.9%, also know as ANSI), which is a superset of ISO-8859-1.
            var streamReader = new StreamReader(stream, Encoding.GetEncoding(1252));
            return streamReader.ReadToEnd();
        }
    }
}

Добавлено через 11 минут
нашел еще на просторах стекОверфлов,
но непонятно будет ли кирилицу хавать….

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
@echo off
setlocal EnableExtensions DisableDelayedExpansion
 
rem // Define constants here:
set "_FILE=%~1" & rem // (provide file via the first command line argument)
 
rem // Check whether a dedicated file is given (so no wild-cards):
2> nul >&2 (< "%_FILE%" set /P ="" & ver) || (
    rem // The file does not exist:
    >&2 echo The file could not be found, hence there is no encoding!
    exit /B 255
)
 
rem // Determine the file size:
set "SIZE=" & for %%F in ("%_FILE%") do set "SIZE=%%~zF"
if not defined SIZE (
    rem // The file does not exist:
    >&2 echo The file could not be found, hence there is no encoding!
    exit /B 255
)
if %SIZE% EQU 0 (
    rem // The file is empty:
    >&2 echo The file is empty, hence encoding cannot be determined!
    exit /B 1
)
 
rem // Store current code page to be able to restore it finally:
for /F "tokens=2 delims=:" %%C in ('chcp') do set /A "$CP=%%C"
rem /* Change to code page 437 (original IBM PC or DOS code page) temporarily;
rem    this is necessary for extended characters not to be converted: */
> nul chcp 437
 
rem // Attempt to read first line from file; this fails if zero-bytes occur:
(
    rem /* The loop does not iterate over an empty file or one with empty lines only;
    rem    therefore, the behaviour is the same as when zero-bytes occur: */
    for /F usebackq^ delims^=^ eol^= %%L in ("%_FILE%") do (
        rem // Abort reading file after first non-empty line:
        goto :NEXT
    )
) || (
    rem /* The `for /F` loop returns a non-zero exit code in case the file is empty,
    rem    contains empty lines only or the first non-empty line contains zero-bytes;
    rem    to determine whether there are zero-bytes, let `find` process the file,
    rem    which removes zero-bytes or converts them to line-breaks, so `for /F` can
    rem    read the file;
    rem    however, `find` would read the whole file, hence do that only for small
    rem    ones and skip that for large ones, such contains zero-bytes most likely: */
    if %SIZE% LEQ 8192 (
        (
            rem // In case the file contains line-breaks only, the loop does not iterate:
            for /F delims^=^ eol^= %%L in ('^< "%_FILE%" find /V ""') do (
                rem // Abort reading file after first non-empty line:
                goto :ZERO
            )
        ) || (
            rem /* The loop did not iterate, so the file contains line-breaks only;
            rem    restore the initial code page prior to termination: */
            > nul chcp %$CP%
            >&2 echo The file holds only empty lines, hence encoding cannot be determined!
            exit /B 1
        )
    )
)
 
rem // This point is reached in case the file contains zero-bytes:
:ZERO
rem // Restore the initial code page prior to termination:
> nul chcp %$CP%
>&2 echo NULL-bytes detected in first line, so file is non-ASCII/ANSI!
exit /B 2
 
rem // This point is reached in case the file does not contain any zero-bytes:
:NEXT
rem /* Build Byte Order Marks (BOMs) for UTF-16-encoded text (Little Endian and Big Endian)
rem    and for UTF-8-encoded text: */
for /F "tokens=1-3" %%A in ('
    forfiles /P "%~dp0." /M "%~nx0" /C "cmd /C echo 0xFF0xFE 0xFE0xFF 0xEF0xBB0xBF"
') do set "$LE=%%A" & set "$BE=%%B" & set "$U8=%%C"
 
rem /* Reset line string variable, then store first line string (1023 bytes at most);
rem    in contrast to `for /F`, this does not skip over blank lines: */
< "%_FILE%" (set "LINE=" & set /P LINE="")
rem // Check whether the first line of the file begins with any of the BOMs:
if not "%LINE:~,2%"=="%$LE%" if not "%LINE:~,2%"=="%$BE%" if not "%LINE:~,3%"=="%$U8%" goto :CONT
rem /* One of the BOMs has been encountered, hence the file is Unicode-encoded;
rem    restore the initial code page prior to termination: */
> nul chcp %$CP%
>&2 echo BOM encountered in first line, so file is non-ASCII/ANSI!
exit /B 4
 
rem // This point is reached in case the file does not appear as Unicode-encoded:
:CONT
rem // Restore the initial code page prior to termination:
> nul chcp %$CP%
echo The file appears to be an ASCII-/ANSI-encoded text.
 
endlocal
exit /B 0

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Как определить кодировку файла?


В моей файловой системе (Windows 7) у меня есть несколько текстовых файлов (это файлы сценариев SQL, если это имеет значение).

При открытии с помощью Notepad ++ в меню «Кодировка» сообщается, что некоторые из них имеют кодировку «UCS-2 Little Endian», а некоторые — «UTF-8 без BOM».

В чем здесь разница? Все они кажутся совершенно правильными сценариями. Как я могу сказать, какие кодировки у файла без Notepad ++?






Ответы:


Файлы обычно указывают свою кодировку с заголовком файла. Есть много примеров здесь . Однако даже читая заголовок, вы никогда не можете быть уверены, какую кодировку файл действительно использует .

Например, файл с первыми тремя байтами 0xEF,0xBB,0xBF, вероятно , является файлом в кодировке UTF-8. Однако это может быть файл ISO-8859-1, который начинается с символов . Или это может быть совершенно другой тип файла.

Notepad ++ делает все возможное, чтобы угадать, какую кодировку использует файл, и в большинстве случаев он делает это правильно. Хотя иногда это не так — поэтому меню «Кодировка» есть, поэтому вы можете отменить его лучшее предположение.

Для двух кодировок вы упоминаете:

  • Файлы «Little Endian UCS-2» — это файлы UTF-16 (основанные на том, что я понимаю из информации здесь ), поэтому, вероятно, начнем с 0xFF,0xFEпервых 2 байтов. Из того, что я могу сказать, Notepad ++ описывает их как «UCS-2», поскольку он не поддерживает определенные аспекты UTF-16.
  • Файлы «UTF-8 без BOM» не имеют байтов заголовков. Вот что означает бит «без спецификации».






Тебе нельзя. Если бы вы могли это сделать, не было бы так много веб-сайтов или текстовых файлов со «случайным бредом». Вот почему кодирование обычно отправляется вместе с полезной нагрузкой в ​​виде метаданных.

В противном случае все, что вы можете сделать, — это «умное предположение», но результат часто неоднозначен, поскольку одна и та же последовательность байтов может быть допустимой в нескольких кодировках.





Как определить кодировку онлайн

Способ 1: 2cyr

Основное предназначение онлайн-сервиса 2cyr заключается в декодировании определенного отрывка текста, однако это не помешает использовать встроенные в него инструменты для определения кодировки, для чего потребуется только скопировать небольшую надпись.

Перейти к онлайн-сервису 2cyr

  1. В самом декодере вставьте скопированный текст в соответствующую форму, используя контекстное меню или горячую клавишу Ctrl + V.
  2. Активация строки для ввода текста при определении кодировки через онлайн-сервис 2cyr

  3. Убедитесь в том, что текст был успешно добавлен, а затем в поле «Выберите кодировку» установите значение «Автоматически (рекомендуется)». Подтвердите распознавание, нажав по кнопке «ОК», которая расположена справа.
  4. Запуск операции определения кодировки после ввода текста через онлайн-сервис 2cyr

  5. Остается только ознакомиться с названием кодировки в поле «Отображается как», чтобы узнать ее.
  6. Просмотр исходной кодировке при распознавании текста через онлайн-сервис 2cyr

  7. Дополнительно вы можете посмотреть перевод ее в читаемый вид, если та нечитабельна, а также узнать, какая кодировка использовалась для этого.
  8. Определение читаемого вида кодировки при ее распознавании через онлайн-сервис 2cyr

  9. В 2cyr есть и другие читаемые варианты, которые можно использовать в своих целях, переключаясь между ними в соответствующих всплывающих меню.
  10. Дополнительные варианты перевода кодировки через онлайн-сервис 2cyr

Ничего не помешает сохранить или запомнить этот онлайн-сервис и обращаться к нему в те моменты, когда требуется перевести кодировку или снова определить ее. Если же этот вариант не подходит, переходите к рассмотрению следующих сайтов.

Способ 2: Online Decoder

Онлайн-сервис под названием Online Decoder тоже умеет определять кодировку текста в автоматическом режиме, а также переводить ее в читаемый вид или любые другие кодировки, если это требуется. Подбор символов на этом сайте осуществляется буквально в несколько кликов.

Перейти к онлайн-сервису Online Decoder

  1. Воспользуйтесь ссылкой выше или самостоятельно откройте главную страницу сайта Online Decoder, где сразу же активируйте поле для ввода и вставьте туда целевой текст.
  2. Активация поля для вставки текста при определении кодировки через онлайн-сервис Online Decoder

  3. Напротив пункта «Раскодировать текст автоматически (рекомендуется)» нажмите по кнопке «Подбор» для запуска процесса распознавания.
  4. Кнопка для подбора кодировки через онлайн-сервис Online Decoder

  5. Та кодировка, в которую выполнен перевод, отображается второй.
  6. Просмотр конечной кодировки при ее распознавании через онлайн-сервис Online Decoder

  7. Исходная находится прямо после надписи «Я знаю нужные кодировки». Ее и надо узнать, если речь идет об определении стилистики символов.
  8. Просмотр исходной кодировки при ее распознавании через онлайн-сервис Online Decoder

    Lumpics.ru

  9. Перевод в выбранную конечную кодировку вы видите внизу, можете его изменить или скопировать.
  10. Просмотр читаемого вида текста при распознавании кодировки через онлайн-сервис Online Decoder

  11. Используйте дополнительные инструменты сайта Online Decoder, если нужно продолжить взаимодействие с другими надписями.
  12. Дополнительные инструменты взаимодействия с онлайн-сервисом Online Decoder при распознавании кодировки

Способ 3: FoxTools

FoxTools — еще один онлайн-сервис, основное предназначение которого заключается в декодировании текста, однако его функциональность можно использовать и для определения необходимого символьного набора, что происходит так:

Перейти к онлайн-сервису FoxTools

  1. Активируйте поле для ввода и вставьте туда скопированную ранее надпись.
  2. Активация поля для ввода для распознавания кодировки через онлайн-сервис FoxTools

  3. Снизу поля «Исходная кодировка» вы найдете кнопку «Определить», по которой и следует нажать для запуска процесса распознавания.
  4. Кнопка для определения кодировки при ее распознавании через онлайн-сервис FoxTools

  5. Если параллельно осуществляется перевод в читаемый вид, выберите его из выпадающего меню сверху.
  6. Отображение читаемого вида текста при распознавании кодировки через онлайн-сервис FoxTools

  7. Нажмите «Отправить», чтобы получить результат со всей необходимой информацией.
  8. Кнопка для отправки исправления кодировки через онлайн-сервис FoxTools

  9. Ознакомьтесь с параметром возле пункта «Исходная кодировка» для определения символьного набора. Если он отображен не в кодовом названии, найдите перевод через Википедию для общего понимания.
  10. Проверка исходной кодировки при ее проверке через онлайн-сервис FoxTools

  11. Иногда FoxTools не распознает редко используемые кодировки, поэтому потребуется переключиться в режим «Все кодировки» и повторить процедуру подбора.
  12. Переключение между кодировками при использовании онлайн-сервиса FoxTools

Еще статьи по данной теме:

Помогла ли Вам статья?

Понравилась статья? Поделить с друзьями:
  • Как определить дату установки windows 10
  • Как определить кодек bluetooth windows 10
  • Как определить код активации windows 7
  • Как определить главный монитор windows 10
  • Как определить когда включали компьютер windows 10