Error illegal character ufeff

I got an Eclipse project source code(I was told that on Android Studio, maybe they just confused), and I start to migrating the code to android studio refers to http://developer.android.com/sdk/

I got an Eclipse project source code(I was told that on Android Studio, maybe they just confused), and I start to migrating the code to android studio refers to

http://developer.android.com/sdk/installing/migrate.html

But it doesn’t work.
so I import the project from path directly and it transfers to the android-studio project automatically, but still, something wrong when I am compiling.

Error:(1, 1) error: illegalcharacter: ‘ufeff’

the error position refers to

package com.bla.blabla;

Please help me, thanks

Ahmad Aghazadeh's user avatar

asked Apr 22, 2014 at 6:03

Bruce's user avatar

6

That’s a problem related to BOM (Byte Order Mark) character. Byte Order Mark
BOM is a Unicode character used for defining a text file byte order and comes in the start of the file. Eclipse doesn’t allow this character at the start of your file, so you must delete it. For this purpose, use a rich text editor, such as Notepad++, and save the file with encoding «UTF-8 without BOM.» That should remove the problem.

Community's user avatar

answered Feb 22, 2015 at 22:31

Diamond's user avatar

DiamondDiamond

5985 silver badges14 bronze badges

4

Android studio file encoding

On lower-right corner, you can set the file encoding. Select another option than UTF-8

If a popup appear, choose the option Convert.

answered May 12, 2015 at 19:28

Marcelo Amorim's user avatar

0

As Marcelo told, I changed file Encoding option to UTF-16. Ran it, But didn’t work. Again changed to UTF-8 and Converted it. It ran successfully. If above solution doesn’t work, try this.

answered Nov 11, 2015 at 5:50

Darshn's user avatar

DarshnDarshn

1,4821 gold badge21 silver badges30 bronze badges

enter image description hereAt bottom right of the project change file encoding UTF-8 to UTF-16.

  1. A new dialog will get open. Select convert it and run it.
  2. It will give you some errors then again change UTF-16 to UTF-8.
  3. Convert it and run the project. This time your project will run successfully.

answered Feb 15, 2017 at 11:02

Muhammad Laraib Khan's user avatar

2

i solved this problem with this method :

  1. ctrl + A in my activity and copy all codes
  2. delete YourClass.java
  3. create YourClass.java
  4. paste all code in new java class

This method worked for me. tnx

answered Sep 11, 2018 at 8:02

Ali Yazdanifar's user avatar

I was facing this error in intelliJ-2016.1.2.

Thank you @Darsh for your help,
I did same thing, first changed to UTF-16 (i.e convert into UTF-16) and compiled the code. it didn’t work, then again changed back to the UTF-8, this time it worked fine.

Thank you.

answered Jul 7, 2016 at 8:04

Sahil Verma's user avatar

Sahil VermaSahil Verma

1313 silver badges12 bronze badges

2

Above are great solutions. However, if none of them works, try this one:

Open the file in Notepad++;
Copy everything;
Create a new file with the same name;
Paste everything;
Save it.

Now it is gone.

answered Oct 28, 2016 at 19:33

Kai Wang's user avatar

Kai WangKai Wang

3,2851 gold badge30 silver badges27 bronze badges

I tried several of the other answers here with no joy.

In the end I simply deleted the offending line and rewrote it directly into Android Studio. The error disappeared.

Was this caused by me copying and pasting the line of code from youtube (or whatever random blog I was looking at at the time)?

answered Dec 14, 2016 at 17:02

mmmartinnn's user avatar

mmmartinnnmmmartinnn

3874 silver badges16 bronze badges

You can try to this method:

  1. Rename the class like class1.java
  2. Create a new class some renamed class like class.java
  3. Select all contain renamed file and copy into the new class.

This method work for me.

answered Oct 12, 2017 at 7:26

Ahmad Aghazadeh's user avatar

Ahmad AghazadehAhmad Aghazadeh

16.4k11 gold badges101 silver badges97 bronze badges

0

Close android studio and reopen it. It works for me. Furthermore this could happen if you are copying a comment from youtube for example and pasting it into your project

answered Jun 7, 2017 at 20:00

Curio's user avatar

CurioCurio

1,2762 gold badges13 silver badges34 bronze badges

I try using sublime, open the file then «Save with Encoding» there choose UTF-8 (without BOM), and it works :)

answered Apr 6, 2018 at 14:49

Bonnie Milian's user avatar

Simply go in notepad plus plus and open your file and in encoding option at the top bar just select utf8

answered Mar 4, 2019 at 7:18

OPEN LOOPView.java File First

Convert Your UTF8 To ISO 8859-1 TO Solve your problem In andorid Studio

If UTf-8 not show in android studio bottom bar then ctl+shift+n open LoopView Class then so Bottom Bar

enter image description here

enter image description here

Note ISO-8859-1 Use this

If your error not resolved then Invalidate cache and Restart again and

gradlew clean
npm start — —reset-cache
react-native run-android
react-native run-ios

Solve Your issue permenantly

One Other Thing if issue still persist then com.wheel file copy into notepad++ and again copy and paste in your project

 android {  
   compileOptions.encoding = 'ISO-8859-1'
 }

In React-native change in index.js / android/index.js

import PropTypes from ‘prop-types’;

answered Sep 25, 2019 at 7:12

Keshav Gera's user avatar

Keshav GeraKeshav Gera

10.6k1 gold badge74 silver badges52 bronze badges

2

Just delete the first line of the xml-file and retype it by hand (copy paste would reinsert the hidden BOM).

answered Sep 5, 2019 at 16:18

Stefano Mader's user avatar

The ideas in here certainly helped me but the outcome was a little different.

I did convert my file encoding from UTF-8 to UTF-16. I was then presented with a different error. When i converted it back to UTF-8, I noted that there was a string of unrecognizable characters before my code line. I removed them and recompiled and it worked well.

My conclusion is somehow an unrecognizable character snuck into my code. Could be programmer error, or a blind copy/paste from the web that placed a nasty hidden character. Carrying the process above as outlined by our peers here somehow allowed me to see it.

If you’ll follow this idea above, please make sure to clean/rebuild between each conversion.

answered Mar 8, 2020 at 3:54

Sol Sadek's user avatar

1. Overview

The illegal character compilation error is a file type encoding error. It’s produced if we use an incorrect encoding in our files when they are created. As result, in languages like Java, we can get this type of error when we try to compile our project. In this tutorial, we’ll describe the problem in detail along with some scenarios where we may encounter it, and then, we’ll present some examples of how to resolve it.

2.1. Byte Order Mark (BOM)

Before we go into the byte order mark, we need to take a quick look at the UCS (Unicode) Transformation Format (UTF). UTF is a character encoding format that can encode all of the possible character code points in Unicode. There are several kinds of UTF encodings. Among all these, UTF-8 has been the most used.

UTF-8 uses an 8-bit variable-width encoding to maximize compatibility with ASCII. When we use this encoding in our files, we may find some bytes that represent the Unicode code point. As a result, our files start with a U+FEFF byte order mark (BOM). This mark, correctly used, is invisible. However, in some cases, it could lead to data errors.

In the UTF-8 encoding, the presence of the BOM is not fundamental. Although it’s not essential, the BOM may still appear in UTF-8 encoded text. The BOM addition could happen either by an encoding conversion or by a text editor that flags the content as UTF-8.

Text editors like Notepad on Windows could produce this kind of addition. As a consequence, when we use a Notepad-like text editor to create a code example and try to run it, we could get a compilation error. In contrast, modern IDEs encode created files as UTF-8 without the BOM. The next sections will show some examples of this problem.

2.2. Class with Illegal Character Compilation Error

Typically, we work with advanced IDEs, but sometimes, we use a text editor instead. Unfortunately, as we’ve learned, some text editors could create more problems than solutions because saving a file with a BOM could lead to a compilation error in Java. The “illegal character” error occurs in the compilation phase, so it’s quite easy to detect. The next example shows us how it works.

First, let’s write a simple class in our text editor, such as Notepad. This class is just a representation – we could write any code to test. Next, we save our file with the BOM to test:

public class TestBOM {
    public static void main(String ...args){
        System.out.println("BOM Test");
    }
}

Now, when we try to compile this file using the javac command:

$ javac ./TestBOM.java

Consequently, we get the error message:

public class TestBOM {
 ^
.TestBOM.java:1: error: illegal character: 'u00bf'
public class TestBOM {
  ^
2 errors

Ideally, to fix this problem, the only thing to do is save the file as UTF-8 without BOM encoding. After that, the problem is solved. We should always check that our files are saved without a BOM.

Another way to fix this issue is with a tool like dos2unix. This tool will remove the BOM and also take care of other idiosyncrasies of Windows text files.

3. Reading Files

Additionally, let’s analyze some examples of reading files encoded with BOM.

Initially, we need to create a file with BOM to use for our test. This file contains our sample text, “Hello world with BOM.” – which will be our expected string. Next, let’s start testing.

3.1. Reading Files Using BufferedReader

First, we’ll test the file using the BufferedReader class:

@Test
public void whenInputFileHasBOM_thenUseInputStream() throws IOException {
    String line;
    String actual = "";
    try (BufferedReader br = new BufferedReader(new InputStreamReader(file))) {
        while ((line = br.readLine()) != null) {
            actual += line;
        }
    }
    assertEquals(expected, actual);
}

In this case, when we try to assert that the strings are equal, we get an error:

org.opentest4j.AssertionFailedError: expected: <Hello world with BOM.> but was: <Hello world with BOM.>
Expected :Hello world with BOM.
Actual   :Hello world with BOM.

Actually, if we skim the test response, both strings look apparently equal. Even so, the actual value of the string contains the BOM. As result, the strings aren’t equal.

Moreover, a quick fix would be to replace BOM characters:

@Test
public void whenInputFileHasBOM_thenUseInputStreamWithReplace() throws IOException {
    String line;
    String actual = "";
    try (BufferedReader br = new BufferedReader(new InputStreamReader(file))) {
        while ((line = br.readLine()) != null) {
            actual += line.replace("uFEFF", "");
        }
    }
    assertEquals(expected, actual);
}

The replace method clears the BOM from our string, so our test passes. We need to work carefully with the replace method. A huge number of files to process can lead to performance issues.

3.2. Reading Files Using Apache Commons IO

In addition, the Apache Commons IO library provides the BOMInputStream class. This class is a wrapper that includes an encoded ByteOrderMark as its first bytes. Let’s see how it works:

@Test
public void whenInputFileHasBOM_thenUseBOMInputStream() throws IOException {
    String line;
    String actual = "";
    ByteOrderMark[] byteOrderMarks = new ByteOrderMark[] { 
      ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE
    };
    InputStream inputStream = new BOMInputStream(ioStream, false, byteOrderMarks);
    Reader reader = new InputStreamReader(inputStream);
    BufferedReader br = new BufferedReader(reader);
    while ((line = br.readLine()) != null) {
        actual += line;
    }
    assertEquals(expected, actual);
}

The code is similar to previous examples, but we pass the BOMInputStream as a parameter into the InputStreamReader.

3.3. Reading Files Using Google Data (GData)

On the other hand, another helpful library to handle the BOM is Google Data (GData). This is an older library, but it helps manage the BOM inside the files. It uses XML as its underlying format. Let’s see it in action:

@Test
public void whenInputFileHasBOM_thenUseGoogleGdata() throws IOException {
    char[] actual = new char[21];
    try (Reader r = new UnicodeReader(ioStream, null)) {
        r.read(actual);
    }
    assertEquals(expected, String.valueOf(actual));
}

Finally, as we observed in the previous examples, removing the BOM from the files is important. If we don’t handle it properly in our files, unexpected results will happen when the data is read. That’s why we need to be aware of the existence of this mark in our files.

4. Conclusion

In this article, we covered several topics regarding the illegal character compilation error in Java. First, we learned what UTF is and how the BOM is integrated into it. Second, we showed a sample class created using a text editor – Windows Notepad, in this case. The generated class threw the compilation error for the illegal character. Finally, we presented some code examples on how to read files with a BOM.

As usual, all the code used for this example can be found over on GitHub.

Table of Contents

During a start-up of a StarCCM+ run on Neumann, i encountered a problem.

The macro was copyied/send from a Windows machine to linux(Neumann).

Symptome <feff>

After StarCCM has started up the following message was shown in the log file.

[...]
Loading module: StarSweptMesher
Loading module: RsTurbModel
Loading module: PassiveScalarModel
Simulation database saved by:
  STAR-CCM+ 13.02.013 (linux-x86_64-2.12/gnu6.2-r8) Mon Mar 19 17:33:56 UTC 2018 Np=8
Loading into:
  STAR-CCM+ 13.02.013 (linux-x86_64-2.12/gnu6.2-r8) Mon Mar 19 17:33:56 UTC 2018 Np=32
Object database load completed.
Playing macro: /scratch/tmp/seengel/nozzle/sims/steady/Re3500/RSMellip/m1/macro.java
/scratch/tmp/seengel/nozzle/sims/steady/Re3500/RSMellip/m1/macro.java:1: error: illegal character: 'ufeff'
<feff>// Written by Sebastian Engel 11/2017
^
/scratch/tmp/seengel/nozzle/sims/steady/Re3500/RSMellip/m1/macro.java:5: error: class, interface, or enum expected
import java.util.concurrent.*;  // to convert milliseconds to seconds
^
 
error: /scratch/tmp/seengel/nozzle/sims/steady/Re3500/RSMellip/m1/macro.java:1: error: illegal character: 'ufeff'
<feff>// Written by Sebastian Engel 11/2017
^
/scratch/tmp/seengel/nozzle/sims/steady/Re3500/RSMellip/m1/macro.java:5: error: class, interface, or enum expected
import java.util.concurrent.*;  // to convert milliseconds to seconds
^
 
Design STAR-CCM+ simulation completed
Server process exited with code : 0

When looking into the file, there was no additional character.

Cause: BOM

A quick google search revealed that ufeff is a Byte-Order-Mark, something like a file format indicator.

StarCCM, or UNIX or JAVA might not like such a mark. Therefore it has to be removed.

Snippet from Wikipedia: Byte order mark

The byte order mark (BOM) is a particular usage of the special Unicode character, U+FEFF BYTE ORDER MARK, whose appearance as a magic number at the start of a text stream can signal several things to a program reading the text:

  • The byte order, or endianness, of the text stream in the cases of 16-bit and 32-bit encodings;
  • The fact that the text stream’s encoding is Unicode, to a high level of confidence;
  • Which Unicode character encoding is used.

BOM use is optional. Its presence interferes with the use of UTF-8 by software that does not expect non-ASCII bytes at the start of a file but that could otherwise handle the text stream.

Unicode can be encoded in units of 8-bit, 16-bit, or 32-bit integers. For the 16- and 32-bit representations, a computer receiving text from arbitrary sources needs to know which byte order the integers are encoded in. The BOM is encoded in the same scheme as the rest of the document and becomes a noncharacter Unicode code point if its bytes are swapped. Hence, the process accessing the text can examine these first few bytes to determine the endianness, without requiring some contract or metadata outside of the text stream itself. Generally the receiving computer will swap the bytes to its own endianness, if necessary, and would no longer need the BOM for processing.

The byte sequence of the BOM differs per Unicode encoding (including ones outside the Unicode standard such as UTF-7, see table below), and none of the sequences is likely to appear at the start of text streams stored in other encodings. Therefore, placing an encoded BOM at the start of a text stream can indicate that the text is Unicode and identify the encoding scheme used. This use of the BOM character is called a «Unicode signature».

Solution: Remove BOM

In Unix:

  • run this command. Replace <filename> with the macro which failed.

    sed -i '1s/^xEFxBBxBF//' <filename>
  • The same can be achieved with

    vim <filename> "+set nobomb" "+wq"

In Windows:

  • Open file in Notepad++. (Download here)

  • Open the menu Encoding (ger: Kodierung).

  • Select Convert to UTF-8

  • Save the file, and transfer again.

Back to top

Содержание

  1. Illegal Character ufeff Problem
  2. Symptome
  3. Cause: BOM
  4. Русские Блоги
  5. Ошибка компиляции Java под Linux: нелегальный характер: ‘ ufeff’
  6. Решение
  7. error illegal character u00bb
  8. 9 Answers 9
  9. error: illegal character: ‘u00a0’ #475
  10. Comments
  11. Ошибка недопустимого символа при компиляции исходных кодов Java
  12. 4 ответы

Illegal Character ufeff Problem

During a start-up of a StarCCM+ run on Neumann, i encountered a problem.
The macro was copyied/send from a Windows machine to linux(Neumann).

Symptome

After StarCCM has started up the following message was shown in the log file.

When looking into the file, there was no additional character.

Cause: BOM

A quick google search revealed that ufeff is a Byte-Order-Mark, something like a file format indicator.
StarCCM, or UNIX or JAVA might not like such a mark. Therefore it has to be removed.

The byte order mark (BOM) is a particular usage of the special Unicode character, U+FEFF BYTE ORDER MARK , whose appearance as a magic number at the start of a text stream can signal several things to a program reading the text:

  • The byte order, or endianness, of the text stream in the cases of 16-bit and 32-bit encodings;
  • The fact that the text stream’s encoding is Unicode, to a high level of confidence;
  • Which Unicode character encoding is used.

BOM use is optional. Its presence interferes with the use of UTF-8 by software that does not expect non-ASCII bytes at the start of a file but that could otherwise handle the text stream.

Unicode can be encoded in units of 8-bit, 16-bit, or 32-bit integers. For the 16- and 32-bit representations, a computer receiving text from arbitrary sources needs to know which byte order the integers are encoded in. The BOM is encoded in the same scheme as the rest of the document and becomes a noncharacter Unicode code point if its bytes are swapped. Hence, the process accessing the text can examine these first few bytes to determine the endianness, without requiring some contract or metadata outside of the text stream itself. Generally the receiving computer will swap the bytes to its own endianness, if necessary, and would no longer need the BOM for processing.

The byte sequence of the BOM differs per Unicode encoding (including ones outside the Unicode standard such as UTF-7, see table below), and none of the sequences is likely to appear at the start of text streams stored in other encodings. Therefore, placing an encoded BOM at the start of a text stream can indicate that the text is Unicode and identify the encoding scheme used. This use of the BOM character is called a «Unicode signature».

Источник

Русские Блоги

Ошибка компиляции Java под Linux: нелегальный характер: ‘ ufeff’

Коллеги столкнулись с ошибкой при упаковке Jenkins:

На первый взгляд, в коде есть нелегальный характер, но Ufeff, очевидно, не персонаж, такой как китайский. Заголовок BOM UTF8 — EF BB BF, а онлайн-поиск — это большой конечный заказ UTF16 — FE FF. Поэтому предположение — это проблема, которую коллеги кодируют настройки при записи кода.

BOM Full Name Mark Mark Byte Byte, Chinese Translated «Тег заказа BYTE». Найти описание отсчета здесь:

Есть имя под названием «в кодировке UCS»Zero Width No-Break Space«, Китайский перевод»Нулевая ширина без интервала«Персонажи, его код — FEFF. FFFE не существует в UCS, поэтому он не должен появиться в фактической передаче. Cucs Спецификация предполагает нас в передачеБайтовый потокРаньше отправляйте персонажи «нулевую ширину безразличного пространства». Таким образом, если получатель получает FEFF, этот байтовый поток является Big-Endian; если он получает FFFE, это указывает на то, что этот байтовый поток — это маленький. Следовательно, персонаж «нулевая ширина безрывного пространства» также называется BOM.

Решение

Направляясь на проблему компиляции ошибок на верхней стороне, решение на самом деле очень просто, просто удалите голову BOM. Вы можете сделать это под Linux:

Тогда вы можете увидеть заголовок слова с помощью , удалите его.

Под Windows необходимо иметь дело с инструментами, такими как Notepad ++, откройте файл, строка меню -> Редактировать -> Перейти в UTF-8 без формата BOM.

Источник

error illegal character u00bb

У меня есть исходный код проекта Eclipse (мне сказали, что в Android Studio, может быть, они просто смущены), и я начинаю переносить код в студию Android, ссылаясь на

Но это не сработает. поэтому я напрямую импортирую проект из пути, и он автоматически переносится в проект Android-студии, но все-таки что-то не так, когда я компилирую.

Ошибка: (1, 1) error: disabledcharacter: ‘ ufeff’

позиция ошибки относится к

Пожалуйста, помогите мне, спасибо

Это проблема, связанная с типом BOM (Byte Order Mark). Знак порядка байтов BOM — это символ Юникода, используемый для определения порядка байтов текстового файла и входит в начало файла. Eclipse не разрешает этот символ в начале вашего файла, поэтому вы должны его удалить. Для этого используйте богатый текстовый редактор, например Notepad ++, и сохраните файл с кодировкой «UTF-8 без спецификации». Это должно устранить проблему.

У меня есть программа, которая позволяет пользователю вводить java-код в текстовое поле, а затем компилировать его с помощью java-компилятора. Всякий раз, когда я пытаюсь скомпилировать код, который я написал, я получаю сообщение об ошибке, в котором говорится, что у меня есть незаконный символ в начале моего кода, которого нет. Это ошибка, которую компилятор мне дает:

Спецификация создается, например, File.WriteAllText() или StreamWriter, если вы не указали кодировку. По умолчанию используется кодировка UTF8 и создается спецификация. Вы можете сообщить компилятору java об этом с помощью параметра командной строки -encoding.

Путь наименьшего сопротивления состоит в том, чтобы избежать создания спецификации. Сделайте это, указав System.Text.Encoding.Default, который напишет файл с символами на кодовой странице по умолчанию вашей операционной системы и не будет писать спецификацию. Используйте перегрузку File.WriteAllText(String, String, Encoding) или конструктор StreamWriter (String, Boolean, Encoding).

Просто убедитесь, что созданный вами файл не скомпилируется машиной в другом уголке мира. Он произведет mojibake.

Это знак байтового порядка, как все говорят.

javac не понимает спецификацию, даже когда вы пытаетесь что-то вроде

Вам нужно снять спецификацию или преобразовать исходный файл в другую кодировку. Notepad ++ может преобразовывать единую кодировку файлов, для этого я не знаю о пакетной утилите на платформе Windows.

Компилятор java предполагает, что файл находится в кодировке по умолчанию для платформы, поэтому, если вы используете это, вам не нужно указывать кодировку.

Знак порядка байтов (BOM) — это Unicode символ, используемый для endianness (порядок байтов) текстового файла или поток. Его кодовая точка U + FEFF. Использование спецификации необязательно, и, если используется, должен появиться в начале текста поток. Помимо его конкретного использования в качестве байт-указатель, спецификация символ может также указывать, какой из несколько представлений Unicode текст закодирован.

BOM — это забавный вид, который вы иногда находите в начале потоков Unicode, давая понять, что такое кодировка. Он обычно обрабатывает невидимые элементы обработки строк в Java, поэтому вы должны каким-то образом смутить его, но, не видя своего кода, трудно увидеть, где.

Возможно, вы сможете устранить его тривиально, вручную удалив спецификацию из строки перед ее подачей на javac . Вероятно, он квалифицируется как пробел, поэтому попробуйте называть trim() на входной строке и подавать вывод этого значения на javac .

Я решил это, щелкнув правой кнопкой мыши в своем программном файле textEdit и выбрав [замены] и отключив смарт-кавычки.

I have a program that allows a user to type java code into a rich text box and then compile it using the java compiler. Whenever I try to compile the code that I have written I get an error that says that I have an illegal character at the beginning of my code that is not there. This is the error the compiler is giving me:

9 Answers 9

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don’t specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn’t write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn’t get compiled by a machine in another corner of the world. It will produce mojibake.

That’s a byte order mark, as everyone says.

javac does not understand the BOM, not even when you try something like

You need to strip the BOM or convert your source file to another encoding. Notepad++ can convert a single files encoding, I’m not aware of a batch utility on the Windows platform for this.

The java compiler will assume the file is in your platform default encoding, so if you use this, you don’t have to specify the encoding.

  1. If using an IDE, specify the java file encoding (via the properties panel)
  2. If NOT using an IDE, use an advanced text-editor (I can recommend Notepad++) and set the encoding to «UTF without BOM», or «ANSI», if that suits you.

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. Its code point is U+FEFF. BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

The BOM is a funky-looking character that you sometimes find at the start of unicode streams, giving a clue what the encoding is. It’s usually handles invisibly by the string-handling stuff in Java, so you must have confused it somehow, but without seeing your code, it’s hard to see where.

You might be able to fix it trivially by manually stripping the BOM from the string before feeding it to javac . It probably qualifies as whitespace, so try calling trim() on the input String, and feeding the output of that to javac .

Источник

error: illegal character: ‘u00a0’ #475


make on linux ,I got some error
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:667: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1082: error: illegal character: ‘u00a0’
/**
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
../java/org/zeromq/ZMQ.java:1091: error: illegal character: ‘u00a0’
setLongSockopt(56, handover);
^
25 errors

The text was updated successfully, but these errors were encountered:

I’m seeing the same issue as well. does anyone know how to get around this?

Источник

Ошибка недопустимого символа при компиляции исходных кодов Java

У меня есть ошибки компиляции в моих файлах java:

Это что-то связано с кодировкой?

нам понадобится код здесь! — talnicolas

Вы уверены, что не пытаетесь скомпилировать .class файл? — Mat

Мне кажется, что ошибка кодировки разрыва строки, как уже упоминалось, трудно сказать, не увидев больше. И убедитесь, что вы скомпилировали файл .java, а затем запустили .class, а не наоборот. — bcmoney

Я использовал java 1.7 и столкнулся с этой проблемой. Переход на java 1.6 устранил проблему. — user243655

Я получил это сообщение об ошибке из-за повреждения файловой системы, прямо перед тем, как моя машина разбилась! В моем случае я компилировал файл .java, но он был обнулен после возврата моих изменений в файл. — Drew Noakes

4 ответы

Это похоже на одно из:

Вы пытаетесь скомпилировать файл .class

Компилятор считывает поврежденный файл класса из пути к классам.

Даже я столкнулся с такой же проблемой. Проблема была в формате файла. Просто сохраните файл в формате ANSI, а не в формате Unicode или UTF. В моем случае это сработало! Вы можете просто открыть свой код в блокноте и сохранить как в формате символов кодировки ANSI!

ответ дан 19 дек ’12, 17:12

Я не уверен, что это та же проблема, но может быть. Я заархивировал некоторый исходный код java из Mac OS X, где он компилировался нормально, и скопировал его в Linux, где я получал следующие ошибки:

db / src /._ SomeClass.java:1: ошибка: несопоставимый символ для кодировки UTF8 . db / src /._ SomeClass.java:1: ошибка: недопустимый символ: 0 .

Этого файла не существовало в OS X, но я думаю, что он был создан, когда я распаковал архив, потому что исходный файл .java имел расширенные атрибуты.

Источник

Коллеги столкнулись с ошибкой при упаковке Jenkins:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project cpo: Compilation failure: Compilation failure:
[ERROR] /root/.jenkins/workspace/cpo-uat/src/main/java/com/linkgoo/cpo/module/worktable/entity/AChinaBuyPlan.java:[1,1] illegal character: 'ufeff'
[ERROR] /root/.jenkins/workspace/cpo-uat/src/main/java/com/linkgoo/cpo/module/worktable/entity/AChinaBuyPlan.java:[1,10] class, interface, or enum expected
[ERROR] -> [Help 1]

На первый взгляд, в коде есть нелегальный характер, но Ufeff, очевидно, не персонаж, такой как китайский. Заголовок BOM UTF8 — EF BB BF, а онлайн-поиск — это большой конечный заказ UTF16 — FE FF. Поэтому предположение — это проблема, которую коллеги кодируют настройки при записи кода.

BOM Full Name Mark Mark Byte Byte, Chinese Translated «Тег заказа BYTE». Найти описание отсчета здесь:

Есть имя под названием «в кодировке UCS»Zero Width No-Break Space«, Китайский перевод»Нулевая ширина без интервала«Персонажи, его код — FEFF. FFFE не существует в UCS, поэтому он не должен появиться в фактической передаче. Cucs Спецификация предполагает нас в передачеБайтовый потокРаньше отправляйте персонажи «нулевую ширину безразличного пространства». Таким образом, если получатель получает FEFF, этот байтовый поток является Big-Endian; если он получает FFFE, это указывает на то, что этот байтовый поток — это маленький. Следовательно, персонаж «нулевая ширина безрывного пространства» также называется BOM.

Решение

Направляясь на проблему компиляции ошибок на верхней стороне, решение на самом деле очень просто, просто удалите голову BOM. Вы можете сделать это под Linux:

vi -b AChinaBuyPlan.java

Тогда вы можете увидеть заголовок слова с помощью <FEFF>, удалите его.

Под Windows необходимо иметь дело с инструментами, такими как Notepad ++, откройте файл, строка меню -> Редактировать -> Перейти в UTF-8 без формата BOM.

У меня есть исходный код проекта Eclipse (мне сказали, что в Android Studio, может быть, они просто смущены), и я начинаю переносить код в студию Android, ссылаясь на

http://developer.android.com/sdk/installing/migrate.html

Но это не сработает.
поэтому я напрямую импортирую проект из пути, и он автоматически переносится в проект Android-студии, но все-таки что-то не так, когда я компилирую.

Ошибка: (1, 1) error: disabledcharacter: ‘ ufeff’

позиция ошибки относится к

пакет com.bla.blabla;

Пожалуйста, помогите мне, спасибо

22 апр. 2014, в 08:11

Поделиться

Источник

9 ответов

Это проблема, связанная с типом BOM (Byte Order Mark). Знак порядка байтов
BOM — это символ Юникода, используемый для определения порядка байтов текстового файла и входит в начало файла. Eclipse не разрешает этот символ в начале вашего файла, поэтому вы должны его удалить. Для этого используйте богатый текстовый редактор, например Notepad ++, и сохраните файл с кодировкой «UTF-8 без спецификации». Это должно устранить проблему.

Diamond
22 фев. 2015, в 22:35

Поделиться

Изображение 124501

В правом нижнем углу вы можете установить кодировку файла. Выберите другой вариант, чем UTF-8

Если появится всплывающее окно, выберите вариант Convert.

Marcelo Amorim
12 май 2015, в 20:41

Поделиться

Как сказал Марсело, я изменил параметр кодирования файла на UTF-16. Рана, но не сработала. Снова изменился на UTF-8 и преобразовал его. Он прошел успешно. Если вышеуказанное решение не работает, попробуйте это.

Darsh
11 нояб. 2015, в 07:16

Поделиться

Изображение 124502 Внизу справа от файла изменения файла проекта UTF От -8 до UTF-16.

  • Новое диалоговое окно откроется. Выберите его конвертировать и запустите.
  • Это даст вам некоторые ошибки, а затем снова изменит UTF-16 на UTF-8.
  • Преобразуйте его и запустите проект. На этот раз ваш проект будет успешно работать.

Muhammad Laraib Khan
15 фев. 2017, в 12:32

Поделиться

Я попробовал несколько других ответов здесь без радости.

В конце концов я просто удалил строку нарушения и переписал ее непосредственно в Android Studio. Ошибка исчезла.

Было ли это вызвано тем, что я копировал и вставлял строку кода с youtube (или какой бы случайный блог я не просматривал в то время)?

mmmartinnn
14 дек. 2016, в 18:30

Поделиться

Выше — отличные решения. Однако, если ни одно из них не работает, попробуйте следующее:

Откройте файл в Notepad ++;
Скопируйте все;
Создайте новый файл с тем же именем;
Вставить все;
Сохраните его.

Теперь он ушел.

Kai Wang
28 окт. 2016, в 20:49

Поделиться

Вы можете попробовать этот метод:

  • Переименуйте класс как class1.java
  • Создайте новый класс, переименованный класс, например class.java
  • Выберите все, что содержит переименованный файл и скопируйте его в новый класс.

Этот метод работает для меня.

Ahmad Aghazadeh
12 окт. 2017, в 08:03

Поделиться

Я столкнулся с этой ошибкой в ​​intelliJ-2016.1.2.

Благодарим @Darsh за вашу помощь,
Я сделал то же самое, сначала переключился на UTF-16 (например, конвертировал в UTF-16) и скомпилировал код. он не работал, а затем снова вернулся к UTF-8, на этот раз он работал нормально.

Спасибо.

Sahil Verma
07 июль 2016, в 09:45

Поделиться

Закройте студию android и откройте ее. Это работает для меня.

Curio
07 июнь 2017, в 20:25

Поделиться

Ещё вопросы

  • 1Разработка оранжевого виджета: как перебирать метку графического интерфейса для отображения результатов расчета
  • 1Кодировка HMAC в R против Python
  • 1Как остановить скрипт Python — только если он отлаживается
  • 0JQuery показать и скрыть Div
  • 0Где настраивается версия продукта ID, корпорация и другая информация приложения в C ++
  • 1Обновить доступ к базе данных, c #
  • 1Как найти совпадение одинаковых значений в двух разных столбцах набора данных в Python
  • 1Вызовите метод из представления и получите его значение:
  • 0AngularJS и иерархия охвата
  • 1На маркерных кластерах листовок не отображаются значки
  • 1Обновление данных в datagridview и графическом окне одновременно C #
  • 1Принудительно запустить статическую часть класса без инстанцирования
  • 0Magento — добавить товар в корзину с пользовательским текстом
  • 0Поиск сфинкса — исключить из результатов по условию
  • 1работающий андроид источник из git tree
  • 0Как сохранить значение переменной Python в Telegram в локальной базе данных?
  • 0Chrome favicon.ico GET запрос
  • 0Ubuntu 17.10 — ОШИБКА 2002 (HY000): не удается подключиться к локальному серверу MySQL через сокет ‘/var/run/mysqld/mysqld.sock’ (2)
  • 1Как установить событие на сцене при перетаскивании мышью?
  • 0Подсветка ввода с высотой значения
  • 1Как использовать Two ListView на одном экране?
  • 0Выполнять цикл PHP каждые X секунд
  • 1Как зациклить в Vue.js?
  • 1Есть ли способ расширить уведомления нажатием клавиши, а не касанием?
  • 0jQuery вызов webAPI WebSecurity.IsAuthenticated всегда ложно
  • 0текст вне div в chrome (css)
  • 0Lua обратный вызов из C ++
  • 0SCRIPT438: Объект не поддерживает свойство или метод «делегат»
  • 0Пограничные пиксели перекрываются
  • 1System.ArgumentException: параметр недействителен. GraphicsPath.AddString
  • 0Как использовать QProcess для упаковки telenet.exe в Windows?
  • 0Применение обработчика событий к переменной
  • 1строка JavaScript заменить предложение
  • 1Невозможно получить доступ к моему логическому списку
  • 0Отправить форму и закрыть Fancybox, Javascript
  • 0Как вернуть значение вызова Ajax в angularjs $ scope и связать его с ng-repeat
  • 1Как нарисовать полноэкранный в Android?
  • 1Android — определение элементов любого макета на новом экране (действие)
  • 0Нужен отзывчивый аудиоплеер для всех мобильных (Android, iPhone)
  • 0Сдвиньте поле вверху в правом нижнем углу страницы
  • 0Как открывать ссылки только в новом окне, если установлен флажок
  • 0Скрыть все div по умолчанию при загрузке страницы, отображать: ни один не работает
  • 1Обработка событий пользовательского интерфейса в Android
  • 1<form> отключил мой код JavaScript
  • 1Как реализовать push-уведомления для нескольких приложений Android?
  • 0Как вводить данные SQL, только если ввод не пустой
  • 0как автоматически сфокусироваться на ячейке времени
  • 0_mysql_exceptions.OperationalError
  • 0Yii множественные отношения между разными моделями в разных модулях
  • 1Ошибка значения с tf.round () tenorflow, так как это операция без градиента

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Error illegal character u00bb
  • Error illegal character u00a0
  • Error illegal attribute value
  • Error illegal assignment to for loop variable i
  • Error ignored not own car trace