- Error: Invalid or corrupt jarfile как исправить
- 2 ответа 2
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками java javafx или задайте свой вопрос.
- Связанные
- Похожие
- Подписаться на ленту
- Corrupt jar file
- 12 Answers 12
- Invalid or corrupt jarfile
- error invalid or corrupt jarfile
- 1 ответ 1
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками java javafx или задайте свой вопрос.
- Похожие
- Comments
- ccit-spence commented Apr 13, 2015
- This comment has been minimized.
- dsyer commented Apr 13, 2015
- 3 thoughts on “ Error: Invalid or corrupt jarfile ”
- Leave a Reply Cancel reply
- *** MOROZILKA ***
- Меню навигации
- Пользовательские ссылки
- Информация о пользователе
- не могу запустить Minecraft — Invalid or corrupt jarfile
- Сообщений 1 страница 12 из 12
- Поделиться103-06-2012 03:37:59
- Поделиться203-06-2012 03:38:44
Error: Invalid or corrupt jarfile как исправить
У меня есть javafx проект, я сделал jar файл так: в структуре проекта выбрал Artifacts -> нажал плюс -> JAR -> from modules with dependencies . Далее указал где у меня находится Main класс. После этого забилдил jar файл. Нажимаю я на него а там ошибка следующая: Error: Invalid or corrupt jarfile . Как исправить?
Файл manifest.mf
Структура проекта:
2 ответа 2
В общем idea в не правильный каталог генерирует Manifest файл. Нужно его перекинуть в resources
Если возникает данная ошибка, то необходимо:
- Перенести папку META-INF с файлом MANIFEST.INF в папку resources
- Нажать Build Project (Ctrl+F9)
- После построения нажать Run (Ctrl+F10)
- Проверить на правильность выполнения Вашего кода (в большинстве случаев ошибка пропадает)
Всё ещё ищете ответ? Посмотрите другие вопросы с метками java javafx или задайте свой вопрос.
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.12.20.41044
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Источник
Corrupt jar file
I have created a jar file in windows 7 using eclipse. When I am trying to open the jar file it says invalid or corrupt jar file. Can anyone suggest me why the jar file is invalid?
12 Answers 12
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main() method and have it referenced in MANIFEST.MF .
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn’t doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe , which won’t work for those kind of libary JARs.
This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn’t generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.
The problem occurs when you zip back the folder.
A valid Runnable/Executable JAR has the next structure:
If your JAR complies with these rules it will work doesn’t matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar
Once you’re done try execute it on the command line using:
When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:
The problem might be that there are more than 65536 files in your JAR: Why java complains about jar files with lots of entries? The fix is described in this question’s answer.
Could be because of issue with MANIFEST.MF . Try starting main class with following command if you know the package where main class is located.
This is the common issue with «manifest» in the error? Yes it happens a lot, here’s a link: http://dev-answers.blogspot.com/2006/07/invalid-or-corrupt-jarfile.html
Using the ant task to create the manifest file on-the-fly gives you and entry like:
Creating the manifest file myself, with the bare essentials fixes the issue:
With more investigation I’m sure I could have got the dynamic meta-file creation working with Ant as I know other people do — there must be some peculiarity in the combination of my ant version (1.6.2), java version (1.4.2_07) and perhaps the current phase of the moon.
Notes:
Parsing of the Meta-inf file has been an issue that has come-up, been fixed and then come-up again for sun. See: Bug Id: 4991229. If you can work out if this bug exists in the your (or my) version of the Java SE you have more patience that me.
Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation
As I just came across this topic I wanted to share the reason and solution why I got the message «invalid or corrupt jarfile»:
I had updated the version of the «maven-jar-plugin» in my pom.xml from 2.1 to 3.1.2. Everything still went fine and a jar file was built. But somehow it obviously wouldn’t run anymore.
As soon as i set the «maven-jar-plugin» version back to 2.1 again, the problem was gone.
It can be a typo int the MANIFEST.MF too, p.ex. Build-Date with two :
Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse.
If the jar file has any extra bytes at the end, explorers like 7-Zip can open it, but it will be treated as corrupt. I use an online upload system that automatically adds a single extra LF character (‘\n’, 0x0a) to the end of every jar file. With such files, there are a variety solutions to run the file:
- Use prayagubd’s approach and specify the .jar as the classpath and name of the main class at the command prompt
- Remove the extra byte at the end of the file (with a hex-editor or a command like head -c -1 myjar.jar ), and then execute the jar by double-clicking or with java -jar myfile.jar as normal.
- Change the extension from .jar to .zip, extract the files, and recreate the .zip file, being sure that the META-INF folder is in the top-level.
- Changing the .jar extension to .zip, deleting an uneeded file from within the .jar, and change the extension back to .jar
All of these solutions require that the structure of the .zip and the META-INF file is essentially correct. They have only been tested with a single extra byte at the end of the zip «corrupting» it.
Источник
Invalid or corrupt jarfile
В IntelliJ IDEA-14 создал проект, в параметрах версия Java 1.8, на моем компе запускается и из IDEA, и jar-артифакт. Перенес jar на другой комп, поставил там Java 1.8.66 распоследнюю — пишет такую ошибку при запуске. Про manifesrt ничего не знаю пока, буду читать еще.
Как вообще надо создавать нормальные стандалон-приложения на java?
Скорее всего у тебя действительно повредился файл в процессе переноса.
Ладно, попробую перенести еще раз (как доберусь до компа с исходниками), хотя сомнительно что проблема в этом.
Jar-файл это просто ZIP-архив. Попробуй его разархивировать любым архиватором. Если получится — можно дальше думать. Если не получится — значит файл повреждён.
Фигасе, действительно обычный архив! 🙂 Открывается, там оказывается запихнуто все что надо и не надо из сорцов проекта. Файл вроде не поврежден, как я и подозревал.
Покажи вывод jar tf usergrid-launcher-1.0-SNAPSHOT.jar
Виндовая (знаю где я, не бейте :)) недоконсоль закрывается и не дает прочитать что там написано. Щас буду пробовать победить это и покажу.
«jar» не является внутренней или внешней командой, исполняемой программой или пакетным файлом.
jdk установи для начала
Хороший вопрос. Могу установить конечно, но зачем мне он на машине, где я хочу только запускать готовые приложения? Или Java-программы не будут работать на компах где есть только jre?
Будут, естественно. Но если вам нужно разрабатывать, вам нужен jdk. Почему вы удивляетесь тому, что у вас нет команды jar, если не установлен jdk?
Понял, ради этой команды сейчас качаю и установлю jdk последний. Хотя на этом компе я хотел только запустить программку, которую написал на другом, где она запускается (и где конечно и jre и jdk).
Поставил jdk, написала саксессфулли инсталлед, но jar и javac команды консоль до сих пор не знает. Наверное надо патхи приписывать руками. Не знаю в чем проблема. Как в 17 веке прямо все — консоль, ручное подключение.
В каталоге установленных программ теперь 2 папки — jre1.8.0_66 и jdk1.8.0_66, в которой своя подпапка jre. java -version в консоли пишет версию jre, javac и jar не работают. Перегружался. Монитор протирал. Мыслей нет.
Источник
error invalid or corrupt jarfile
У меня есть javafx проект, я сделал jar файл так: в структуре проекта выбрал Artifacts -> нажал плюс -> JAR -> from modules with dependencies . Далее указал где у меня находится Main класс. После этого забилдил jar файл. Нажимаю я на него а там ошибка следующая: Error: Invalid or corrupt jarfile . Как исправить?
Файл manifest.mf
Структура проекта:
1 ответ 1
В общем idea в не правильный каталог генерирует Manifest файл. Нужно его перекинуть в resources
Всё ещё ищете ответ? Посмотрите другие вопросы с метками java javafx или задайте свой вопрос.
Похожие
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2019 Stack Exchange Inc; пользовательское содержимое попадает под действие лицензии cc by-sa 4.0 с указанием ссылки на источник. rev 2019.11.15.35459
Comments
Copy link Quote reply
ccit-spence commented Apr 13, 2015
I have setup the following Dockerfile. Everything seems to build fine but getting the error that it is corrupt. I did verify that java 8 is set in the POM and manually executed the jar so I know it is working. The other change is that I moved the Dockerfile to the project root. Docker complains about any type of ../ being used to get a path.
Should this work?
This comment has been minimized.
Copy link Quote reply
dsyer commented Apr 13, 2015
It depends on the pom (which you don’t show). Dockerfile ADD works relative to the Dockerfile, so for yours to work you need to copy the jar file to a «target» directory in «target/docker». The maven plugin allows you to do that with a element.
Dan’s technical ramblings
I was creating a Jar via the Java API’s and I couldn’t get it to run my main class:
Running it via the class path worked fine:
So now I knew it was something to do with the manifest file but it wasn’t being caused by
- The 65535 file limit (See Zip64 and Java 7 ).
- The 72 bytes limit per line
- Missing newline at the end of the Main-Class (Displays “no main manifest attribute, in foo.jar”
- A blank line before Main-Class (Displays “Error: An unexpected error occurred while trying to open file foo.jar”
So after scratching my head for a while I tried comparing a working jar with the failing jar:
So don’t prefix the META-INF folder with a slash! Also note it is case sensitive!
3 thoughts on “ Error: Invalid or corrupt jarfile ”
Actually leading slash is forbidden by .ZIP File Format Specification (http://www.pkware.com/documents/casestudies/APPNOTE.TXT). It’s 4.4.17 clause indicate:
The path stored MUST not contain a drive or
device letter, or a leading slash. All slashes
MUST be forward slashes ‘/’ (…).
It’s weird if Java API creates such invalid jars.
Thanks Dan! We had the 65535 jar limit problem and your blog pointed me in the right directions. Ultimately fixed by doing this:
java -jar app.jar
# becomes
java -cp app.jar app.Main
Thank you! Good to know that it could be because of issues with the Manifest.
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Источник
*** MOROZILKA ***
Меню навигации
Пользовательские ссылки
Информация о пользователе
Вы здесь » *** MOROZILKA *** » другие сервера » не могу запустить Minecraft — Invalid or corrupt jarfile
не могу запустить Minecraft — Invalid or corrupt jarfile
Сообщений 1 страница 12 из 12
Поделиться103-06-2012 03:37:59
- Автор: FantOzer
- Админ
- Откуда: Новосибирск
- Зарегистрирован : 09-12-2009
- Приглашений: 0
- Сообщений: 9818
- Уважение: +446
- Позитив: +587
- Пол: Мужской
- Провел на форуме:
4 месяца 13 дней - Последний визит:
Вчера 15:50:59
Не могу запустить Minecraft
Будь проклята эта ява..) на которой работает игра.
она меня уже вымотала.
Помогите кто нибудь запустить игру.
Запускаются без проблема игра та — где НЕвозможно сменить ник..
Игра автоматом ставит имя player и хоть ты тресни.
А при подключени к серверу через какой то время выкидывает..
Если коротко, то лицензия запускается нормально но без регистрации на оф.сайте не дает сменить ник в игре.
А при запуске пиратки, что очень хотелось бы — пишет что файл инвалид.
Поделиться203-06-2012 03:38:44
- Автор: FantOzer
- Админ
- Откуда: Новосибирск
- Зарегистрирован : 09-12-2009
- Приглашений: 0
- Сообщений: 9818
- Уважение: +446
- Позитив: +587
- Пол: Мужской
- Провел на форуме:
4 месяца 13 дней - Последний визит:
Вчера 15:50:59
Ставлю другие сборки, в т.ч. которые стоят у других игроков.. У них все норм, цепляются к серверу.
Но у меня же она даже и не запускается. пишет что — Invalid or corrupt jarfile.
Источник