Java синтаксическая ошибка в имени файла

При попытке ввода любого адреса файла вылезает ошибка:

java.io.FileNotFoundException:C:Program FilesJava11.txt (Синтаксическая ошибка в имени файла, имени папки или метке тома)

Сто раз менял местонахождение файла, его имя, но результат — 0… Подскажите, что может быть??

package com.javarush.task.task13.task1319;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Scanner;

/*
Писатель в файл с консоли
*/

public class Solution {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
try (FileWriter file = new FileWriter(console.nextLine());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(file)){
String str = reader.readLine();
while (reader.ready()){
if (!str.equalsIgnoreCase(«exit»))
writer.write(str);
else {
writer.write(str);
writer.close();
}
}

}
catch (Exception e){
e.printStackTrace();
}
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

введите сюда описание изображенияСоздаю проект в Eclipse IDE, создал class и file в одном и том же месте.
Описал как:

URL urlFnumZ = HelixAtlaskirov.class.getResource("FnumZ.txt");

Если запустить в Eclipse работает на ура, а после сборки jar когда заворачиваю в exe с помощью программы launch4j выдает ошибку:

Caused by: java.io.FileNotFoundException: file:C:GHelix-Lab.exe!atlaskirovhelixjfxFnumZ.txt (Синтаксическая ошибка в имени файла, имени папки или метке тома)

Так же пробовал описать как:

URL urlFnumZ = HelixAtlaskirov.class.getClassLoader().getResource("FnumZ.txt"); то же самое.

задан 13 дек 2018 в 7:12

atlaskirov's user avatar

atlaskirovatlaskirov

291 серебряный знак5 бронзовых знаков

3

Решил тем что поменял метод чтения файла на:

InputStream urlFnumZ = HelixAtlaskirov.class.getResourceAsStream("FnumZ.txt");
Scanner fsNz = new Scanner(urlFnumZ);

Kromster's user avatar

Kromster

13.5k12 золотых знаков43 серебряных знака72 бронзовых знака

ответ дан 13 дек 2018 в 8:05

atlaskirov's user avatar

atlaskirovatlaskirov

291 серебряный знак5 бронзовых знаков

Если фал находится сразу под resources, то нужно добавить слеш:

URL urlFnumZ = HelixAtlaskirov.class.getResource("/FnumZ.txt");

ответ дан 13 дек 2018 в 7:32

Andrii Torzhkov's user avatar

2

I am trying to copy a file using the following code:

File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
    fileOutputStream.write(buffer, 0, i);
}

For some users the targetFile.createNewFile results in this exception:

java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:850)

Filename and directory name seem to be correct. The directory targetPath is even checked for existence before the copy code is executed and the filename looks like this: AB_timestamp.xml

The user has write permissions to the targetPath and can copy the file without problems using the OS.

As I don’t have access to a machine this happens on yet and can’t reproduce the problem on my own machine I turn to you for hints on the reason for this exception.

Dima's user avatar

Dima

38.8k14 gold badges74 silver badges115 bronze badges

asked Sep 25, 2008 at 7:22

Turismo's user avatar

This can occur when filename has timestamp with colons, eg. myfile_HH:mm:ss.csv Removing colons fixed the issue.

answered Feb 16, 2016 at 23:20

Adam Hughes's user avatar

Adam HughesAdam Hughes

14.3k11 gold badges80 silver badges122 bronze badges

2

Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:

File targetFile = new File(targetPath, filename);

answered Sep 25, 2008 at 15:01

Alexander's user avatar

AlexanderAlexander

9,2322 gold badges26 silver badges22 bronze badges

I just encountered the same problem. I think it has to something do with write access permission. I got the error while trying to write to c: but on changing to D: everything worked fine.
Apparently Java did not have permission to write to my System Drive (Running Windows 7 installed on C:)

Sahil Mahajan Mj's user avatar

answered Apr 25, 2010 at 9:56

Sensei's user avatar

SenseiSensei

711 silver badge1 bronze badge

1

Here is the test program I use

import java.io.File;
public class TestWrite {

    public static void main(String[] args) {
        if (args.length!=1) {
            throw new IllegalArgumentException("Expected 1 argument: dir for tmp file");
        }
        try  {
            File.createTempFile("bla",".tmp",new File(args[0]));
        } catch (Exception e) {
            System.out.println("exception:"+e);
            e.printStackTrace();
        }
    }
}

answered Feb 7, 2011 at 12:53

w.pasman's user avatar

1

Try to create the file in a different directory — e.g. «C:» after you made sure you have write access to that directory. If that works, the path name of the file is wrong.

Take a look at the comment in the Exception and try to vary all the elements in the path name of the file. Experiment. Draw conclusions.

answered Sep 25, 2008 at 7:45

xmjx's user avatar

xmjxxmjx

1,1481 gold badge7 silver badges18 bronze badges

Remove any special characters in the file/folder name in the complete path.

answered Jun 26, 2019 at 10:43

urupani's user avatar

1

Do you check that the targetPath is a directory, or just that something exists with that name? (I know you say the user can copy it from the operating system, but maybe they’re typing something else).

Does targetPath end with a File.separator already?

(It would help if you could log and tell us what the value of targetPath and filename are on a failing case)

answered Sep 25, 2008 at 7:28

The Archetypal Paul's user avatar

Maybe the problem is that it is copying the file over the network, to a shared drive? I think java can have problems when writing files using NFS when the path is something like mypcmyshared folder.

What is the path where this problem happens?

answered Sep 25, 2008 at 7:29

Mario Ortegón's user avatar

Mario OrtegónMario Ortegón

18.6k17 gold badges70 silver badges81 bronze badges

Try adding some logging to see exactly what is the name and path the file is trying to create, to ensure that the parent is well a directory.

In addition, you can also take a look at Channels instead of using a loop. ;-)

answered Sep 25, 2008 at 7:30

gizmo's user avatar

gizmogizmo

11.8k6 gold badges44 silver badges61 bronze badges

You say «for some users» — so it works for others? What is the difference here, are the users running different instances on different machines, or is this a server that services concurrent users?

If the latter, I’d say it is a concurrency bug somehow — two threads check try to create the file with WinNTFileSystem.createFileExclusively(Native Method) simultaniously.

Neither createNewFile or createFileExclusively are synchronized when I look at the OpenJDK source, so you may have to synchronize this block yourself.

answered Sep 25, 2008 at 7:39

Lars Westergren's user avatar

1

Maybe the file already exists. It could be the case if your timestamp resolution is not good enough. As it is an IOException that you are getting, it might not be a permission issue (in which case you would get a SecurityException).

I would first check for file existence before trying to create the file and try to log what’s happening.

Look at public boolean createNewFile() for more information on the method you are using.

answered Sep 25, 2008 at 9:29

bernardn's user avatar

bernardnbernardn

1,7015 gold badges19 silver badges23 bronze badges

1

As I was not able to reproduce the error on my own machine or get hands on the machine of the user where the code failed I waited until now to declare an accepted answer.
I changed the code to the following:

File parentFolder = new File(targetPath);
... do some checks on parentFolder here ...
File targetFile = new File(parentFolder, filename);
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
    fileOutputStream.write(buffer, 0, i);
}

After that it worked for the user reporting the problem.

So it seems Alexanders answer did the trick — although I actually use a slightly different constructor than he gave, but along the same lines.

I yet have to talk that user into helping me verifying that the code change fixed the error (instead of him doing something differently) by running the old version again and checking if it still fails.

btw. logging was in place and the logged path seemed ok — sorry for not mentioning that. I took that for granted and found it unnecessarily complicated the code in the question.

Thanks for the helpful answers.

answered Oct 15, 2008 at 9:22

Turismo's user avatar

TurismoTurismo

2,0542 gold badges16 silver badges23 bronze badges

FileUtils.copyFile(src,new File("C:\Users\daiva\eclipse-workspace\PracticeProgram\Screenshot\adi.png"));

Try to copy file like this.

Laurel's user avatar

Laurel

5,94414 gold badges30 silver badges57 bronze badges

answered Nov 11, 2022 at 21:03

user20481302's user avatar

waip

7 / 7 / 1

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

Сообщений: 297

1

06.04.2013, 15:59. Показов 3028. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет
Решил опробовать BufferedReader для чтения файла с веб сервера.
Почти получилось, только программа кидает исключение.

Java
1
2
3
4
5
6
7
8
9
10
11
12
    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        try {
            // TODO code application logic here
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("http:\www.webserver.ru/summ.log")));
    String s =null;
    while((s=br.readLine())!=null){
        System.out.println(s.toString());
    }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaApplication110.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Исключение

апр 06, 2013 10:41:22 PM javaapplication110.JavaApplication110 main
SEVERE: null
java.io.FileNotFoundException: http:www.webserver.rusumm.log (Синтаксическая ошибка в имени файла, имени папки или метке тома)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at javaapplication110.JavaApplication110.main(JavaApplication110.java:22)

Тут все понятно,а именно
(Синтаксическая ошибка в имени файла, имени папки или метке тома)
Вопрос:
Какая может быть ошибка. Уже даже слэши по разному писал — всё одно(



0



68 / 68 / 1

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

Сообщений: 458

06.04.2013, 16:15

2

Цитата
Сообщение от waip
Посмотреть сообщение

Слеши должны быть в одну сторону



0



7 / 7 / 1

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

Сообщений: 297

06.04.2013, 16:16

 [ТС]

3

Цитата
Сообщение от Ванеек
Посмотреть сообщение

Слеши должны быть в одну сторону

не помогает.



0



KuKu

1562 / 1040 / 94

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

Сообщений: 2,995

06.04.2013, 16:30

4

Java
1
2
InputStream is = new URL("https://www.cyberforum.ru/clientscript/vbulletin_vbpost.js").openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.



1



waip

7 / 7 / 1

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

Сообщений: 297

08.04.2013, 15:53

 [ТС]

5

Опять сел. А как скопировать файл с веб сервера?

Умею только локально копировать

Java
1
2
3
FileChannel scrFile = new FileInputStream("C:\1.rar").getChannel();
FileChannel dstFile = new FileOutputStream("D:\1.rar").getChannel(); 
dstFile.transferFrom(scrFile, 0, scrFile.size());



0



2000 / 1427 / 92

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

Сообщений: 3,611

08.04.2013, 17:05

6

Читаете поток байтов с сервера, пишете в файл. Неожиданно, правда?



0



waip

7 / 7 / 1

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

Сообщений: 297

08.04.2013, 17:41

 [ТС]

7

Цитата
Сообщение от Skipy
Посмотреть сообщение

Читаете поток байтов с сервера, пишете в файл. Неожиданно, правда?

т.е читаем строчку файла на веб сервере и записываем в локальный файл?
Два вопроса:
1) Если файл весит 1-2ГБ рационально ли использование такого метода?
2) Не будет ли нарушена кодировка у файла?

Добавлено через 34 минуты

Java
1
2
3
4
5
6
7
8
BufferedReader br = new BufferedReader(new InputStreamReader(new URL("http://webserver/"+FILE_NAME).openStream()));
       BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("data\"+FILE_NAME)));
       String ssd =null;
       while((ssd=br.readLine())!=null){
           bw.write(ssd);
           bw.flush();
           bw.newLine();
       }

Попробовал так. Файл битый приходит(



0



2586 / 2259 / 257

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

Сообщений: 5,185

Записей в блоге: 18

08.04.2013, 18:26

8



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

08.04.2013, 18:26

Помогаю со студенческими работами здесь

Path
Hello!
я очень недавно начала учить Java.
установила jdk1.6_10.
задала Path, для bin, написала…

Вернуть путь Path
Я болван. Установил JDK, зашел в переменные среды, и вместо того что бы добавить, заменил пути. И…

Добавление jars в PATH
Здравствуйте! Решил попробовать JCuda.
JCuda tutorial

Я скачал JCuda архив и добавил к…

java.library.path
При запуске программы выдает след.ошибку:
INFO: The APR based Apache Tomcat Native library which…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

введите сюда описание изображенияСоздаю проект в Eclipse IDE, создал class и file в одном и том же месте.
Описал как:

URL urlFnumZ = HelixAtlaskirov.class.getResource("FnumZ.txt");

Если запустить в Eclipse работает на ура, а после сборки jar когда заворачиваю в exe с помощью программы launch4j выдает ошибку:

Caused by: java.io.FileNotFoundException: file:C:GHelix-Lab.exe!atlaskirovhelixjfxFnumZ.txt (Синтаксическая ошибка в имени файла, имени папки или метке тома)

Так же пробовал описать как:

URL urlFnumZ = HelixAtlaskirov.class.getClassLoader().getResource("FnumZ.txt"); то же самое.

Понравилась статья? Поделить с друзьями:
  • Java virtual machine launcher unable to access jarfile ошибка
  • Java swing сообщение об ошибке
  • Java platform se binary как исправить ошибку
  • Java net sockettimeoutexception read timed out ошибка
  • Java lang reflect invocationtargetexception ошибка причина