Java nio file nosuchfileexception как исправить

I have a file called «result.csv», from that file i want to read certain data and display them. I have that file in my eclipse project folder itself. Still i’m unable to read the file.

 public static void main(String [] args) {
    int i=0;
    String filename="result.csv";
    Path pathToFile = Paths.get(filename);

    try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) { 
        // read the first line from the text file 
        String line = br.readLine(); 
        // loop until all lines are read 
        while (i<10) { 
            // use string.split to load a string array with the values from 
            // each line of 
            // the file, using a comma as the delimiter
            String[] attributes = line.split(","); 
            double x=Double.parseDouble(attributes[8]);
            double y=Double.parseDouble(attributes[9]);
            System.out.println(GeoHash.withCharacterPrecision(x, y, 10));


            // read next line before looping 
            // if end of file reached, line would be null 
            line = br.readLine(); 
            i++;
        } 
    } catch (IOException ioe) { 
            ioe.printStackTrace(); 
    } 
}

OUTPUT:

java.nio.file.NoSuchFileException: result.csv
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at java.nio.file.Files.newBufferedReader(Unknown Source)
at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)

Can anyone point where exactly i missed? and how can i overcome this or any alternate methods for this method?

asked Jan 3, 2018 at 11:02

Snkini's user avatar

SnkiniSnkini

5711 gold badge5 silver badges15 bronze badges

2

The problem is that your default directory at application startup is not what you think it is. Try adding the following line to your code, just after you create the path:

public static void main(String [] args) {
    int i=0;
    String filename="result.csv";
    Path pathToFile = Paths.get(filename);
    System.out.println(pathToFile.toAbsolutePath());

That way, you’ll see exactly where it is looking for the file.

How to fix it is your decision. You can use a full path spec instead of just a filename, or put the filename in a special «Resources» directory and reference it using a relative path, or move the file to wherever your default directory is.

answered Jan 3, 2018 at 11:25

DodgyCodeException's user avatar

2

If your file("result.csv") in the src directory, you should use the «src/result.csv» instead of «result.csv».

answered Sep 22, 2018 at 6:02

何明扬's user avatar

何明扬何明扬

831 silver badge3 bronze badges

1

The problem there is that java isn’t able to find the «result.csv» file in the project folder. Thus, try to use the fully qualified path to the file, e.g. C:your_folderprojectresult.csv in the Path variable. Also I think It would be better to use bufferedreader like this: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file)); Check the uses of BufferedReader here

answered Jan 3, 2018 at 11:26

Alex Cuadrón's user avatar

If you’re a MacOSX user please type the file path manually instead of copying it from «Get Info».
You’ll get something like this if you copied it from «Get Info»:
/Users/username<200e><2068><2068>/Desktop<2069>/source.txt

answered Nov 15, 2018 at 23:20

Nimesh Bumb's user avatar

1

I had the same error caused by escaped characters on windows file path. For example, my application was looking for «C:Usersdavidmy%20folder%20namesource.txt» meanwhile the real path was «C:Usersdavidmy folder namesource.txt«.

answered Sep 28, 2021 at 15:15

Dovydas Giršvaldas's user avatar

Not discarding all possible solutions here, this error also occurs when your running Android Studio on Windows environment and using a project directory on an external hard drive formatted with other than NFTS. ]

If this is the case, simply move your project into the main HDD (NTFS) and reload the project again , this time from the main HDD folder path.

sideshowbarker's user avatar

answered Nov 28, 2021 at 10:50

Miguel Tomás's user avatar

NoSuchFileException occurred when trying to attempt access a file or directory which is not exist in given location.

NoSuchFileException is sub class of FileSystemException. This exception  introduced in Java 7.

Example for NoSuchFileException

This example is throwing NoSuchFileException because trying to access a file student_data.json which is not exist on default location.

package com.fiot.json.jackson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fiot.json.jackson.pojo.Student;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get("student_data.json"));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List studentList=Arrays.asList(studentArr);
		System.out.println("Student 1 n"+studentList.get(0));
		System.out.println("Student 2 n"+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


java.nio.file.NoSuchFileException: student_data.json
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.readAllBytes(Unknown Source)
    at com.fiot.json.jackson.ConvertJsonToArrayList.main(ConvertJsonToArrayList.java:18)

Solutions

There are couple of solutions to handle such situations:

  1. Use fully qualified file path such as “C:/data/student_data.json” but that will help only when your program is going to run on local machine. While working with enterprise application always use relative paths.
  2. If your file in source directory use path as “src/student_data.json”
  3. If your project is maven project, always write script to copy file which you want to access or keep in resource folder to access because maven project create different directory structure after build.

Solution depend on your project requirement. You can use below code to get qualified full path of a file

public static void main(String [] args) {

    String filename="student_data.json";
    //To get path of file
    Path path = Paths.get(filename);
    //To print absolute path of file
    System.out.println(path.getAbsolutePath());

You would like to see

Follow below link to see more Java issues solutions

  • JAVA Issues and Solutions

“Learn From Others Experience»

Have you ever tried reading resources (json files, htm templates, text files etc) in your Spring Boot project, but got a java.nio.file.NoSuchFileException?
confused
The NoSuchFileException occurs if the file is not in the specified location. A similar exception that occurs is the FileNotFoundException.

1. Loading Files from a directory

A common approach developers use to add resources is to place the files in the src/main/resources/ directory, and then read the files from that path.
Although not the best practice, this approach works if the project is run locally. This is because the project directory is used as the current working directory during runtime.

For example, using the code below, I can read user data from a file and save the value in a string.

application.properties

filePath=src/main/resources/filename.txt

Enter fullscreen mode

Exit fullscreen mode

ReadUserDataFromFile.java

public class ReadUserDataFromFile {
   @Value("${filePath}")
   private String dataFilePath;

   public String readDataFile() throws IOException {
      String data = new String(Files.readAllBytes(Paths.get(filePath)));
     return data;
    }
}

Enter fullscreen mode

Exit fullscreen mode

The file is successfully read if it is in the src/main/resources/ directory.

Now, if the project is packaged as a JAR file, the NoSuchFileException will be thrown when trying to read the file. This happens because filename.txt is at the root folder of the JAR and it cannot be accessed using the file path.

2. Creating a Resource object

A better approach and a solution to the NoSuchFileException is to create a org.springframework.core.io.Resource object in your class and set the value to point to the file.
Example:

ReadUserDataFromFile.java

public class ReadUserDataFromFile {
   @Value("classpath:filename.txt")
   private Resource dataFile;

   public String readDataFile() throws IOException {
      String data = new String(dataFile.getInputStream().readAllBytes());
      return data;
    }
}

Enter fullscreen mode

Exit fullscreen mode

With this approach, the file can be read both locally and from JAR file.

This quick coding tip explains how to resolve error java.nio.file.NoSuchFileException when using NIO API in Java.

If you are getting the following exception at runtime –

java.nio.file.NoSuchFileException: C:JavaBrahmanLEVEL11
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:53)
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:38)
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:193)
at java.nio.file.Files.readAttributes(Files.java:1737)
at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219)
at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276)
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322)
at java.nio.file.Files.walkFileTree(Files.java:2662)
at java.nio.file.Files.walkFileTree(Files.java:2742)
at com.javabrahman.corejava.RecursiveFileVisitor.main(RecursiveFileVisitor.java:39)
...

Resolution for the java.nio.file.NoSuchFileException error

  • This error occurs most commonly when a file name, directory name or file path has been incorrectly specified when using the file handling classes of java.nio.file package.
  • You need to closely check the file path you have given in the Java class written by you. This file or directory path will be printed on the top line of the error stack trace as well. Just as C:JavaBrahmanLEVEL11 is printed at the top of the above stack trace.
  • The errant Java class will be present in the middle of the stack trace, between the NIO package’s internal calls, along with the error causing line number. In the above stack trace the error causing file is – (RecursiveFileVisitor.java:39).
  • Also note that, java.nio.file.NoSuchFileException is most likely to be thrown when creating an instance of java.nio.file.Path instance with an incorrect directory path or file name.

Digiprove sealCopyright © 2014-2022 JavaBrahman.com, all rights reserved.

Ошибка java.nio.file.NoSuchFileException: ... server-resource-packs в TLauncher

Ошибка java.nio.file.NoSuchFileException: C:UsersadminAppDataRoaming.minecraftserver-resource-packs возникает при запуске TLauncher, в связи с отсутствием необходимой папки server-resource-packs в .minecraft

Примечание:

Проблема может проявится: в TLauncher версии <2.22

Исправлено: Исправлено в новых версиях лаунчера. TLauncher для Windows и TLauncher для Linux/MacOS.

Исправить вручную без перекачивания лаунчера:

1) Перейдите в папку C:UsersЮЗЕРAppDataRoaming.minecraft , где ЮЗЕР имя вашего компьютера.

2) Создайте папку с именем server-resource-packs

P.S. Если нет папки .minecraft , её можно так же создать вручную.

Если Ваша проблема остаётся актуальной, запросите поддержку у TLauncher:

Написать разработчикам с помощью VK.com

Понравилась статья? Поделить с друзьями:
  • Как найти вторая половинка девушка
  • Как найти деловую репутацию
  • Дочка подросток как найти общий язык
  • Как найти время истечения
  • Как найти фею в игре винкс