I put the test.txt file in the same directory as the main method. In the main method I write the following:

 InputStream in = new BufferedInputStream(new FileInputStream("test.txt")); 

In response, I get:

 java.io.FileNotFoundException: test.txt (Нет такого файла или каталога) 

The main class from which I run the application is in the directory src/decorator/inputStreamExample/ . test.txt there.

What am I doing wrong ?

  • one
    How do you run the program? What is the current / working directory? - Igor
  • I'm not well-versed in terms of the Java language. What does "in the same directory as the main method" mean? The directories are files, not methods. What does "class from which I start" means. Is the program starting from class? Explain somebody, please. - Igor
  • @Igor but is it possible that in C # the program is launched from a static main method? - faoxis
  • I also like to answer the question with a question :). No, in C # static Main is part of the program. - Igor

2 answers 2

I tried to load your code in idea, but there really is an error. Here is the edited version:

 public class FileOpen { public static void main(String[] args) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream("src/java/Text.txt")); System.out.println(in.available()); } } 

You have errors with the file path. Try "src / decorator / inputStreamExample / test.txt". And also, look where you have the source label. Now I checked: if the marking is on src and then create a package there, there is another one in it and there is already a class with a text file, then there will also be errors. If in src you create one package, there is a class with a file in it, then everything is normally searched.

  • Your code does not work. The FileInputStream constructor expects both a variable of type File and String or FileDescriptor, this has nothing to do with it. In addition, you are creating a new file, instead of reading from an existing one, as intended by the author. - Rostyk Shevtsiv
  • @RostykShevtsiv I am not creating a new file here "File file = new File (" Text.txt ");" see the constructor for the File class. - Vladislav Kuznetsov
  • Updated the answer. Criticize ... - Vladislav Kuznetsov
  • Sorry, I meant define a file that does not need it. - Rostyk Shevtsiv
  • one
    Let's continue the discussion in the chat . - Rostyk Shevtsiv

You should use the following construction: InputStream in = new BufferedInputStream(ClassName.class.getResourceAsStream("test.txt")); Where ClassName is the name of your class.