При попытке ввода любого адреса файла вылезает ошибка:
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
atlaskirovatlaskirov
291 серебряный знак5 бронзовых знаков
3
Решил тем что поменял метод чтения файла на:
InputStream urlFnumZ = HelixAtlaskirov.class.getResourceAsStream("FnumZ.txt");
Scanner fsNz = new Scanner(urlFnumZ);
Kromster
13.5k12 золотых знаков43 серебряных знака72 бронзовых знака
ответ дан 13 дек 2018 в 8:05
atlaskirovatlaskirov
291 серебряный знак5 бронзовых знаков
Если фал находится сразу под resources, то нужно добавить слеш:
URL urlFnumZ = HelixAtlaskirov.class.getResource("/FnumZ.txt");
ответ дан 13 дек 2018 в 7:32
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
38.8k14 gold badges74 silver badges115 bronze badges
asked Sep 25, 2008 at 7:22
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 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
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:)
answered Apr 25, 2010 at 9:56
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
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
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
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
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ó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
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
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
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
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
5,94414 gold badges30 silver badges57 bronze badges
answered Nov 11, 2022 at 21:03
waip 7 / 7 / 1 Регистрация: 27.05.2011 Сообщений: 297 |
||||
1 |
||||
06.04.2013, 15:59. Показов 3028. Ответов 7 Метки нет (Все метки)
Всем привет
Исключение апр 06, 2013 10:41:22 PM javaapplication110.JavaApplication110 main Тут все понятно,а именно
0 |
68 / 68 / 1 Регистрация: 21.12.2012 Сообщений: 458 |
|
06.04.2013, 16:15 |
2 |
Слеши должны быть в одну сторону
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 |
|||
FileInputStream(String name)
1 |
waip 7 / 7 / 1 Регистрация: 27.05.2011 Сообщений: 297 |
||||
08.04.2013, 15:53 [ТС] |
5 |
|||
Опять сел. А как скопировать файл с веб сервера? Умею только локально копировать
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 |
|||
Читаете поток байтов с сервера, пишете в файл. Неожиданно, правда? т.е читаем строчку файла на веб сервере и записываем в локальный файл? Добавлено через 34 минуты
Попробовал так. Файл битый приходит(
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 Вернуть путь Path Добавление jars в PATH Я скачал JCuda архив и добавил к… java.library.path Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 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"); то же самое.