How do open the file in the bag?



  • Java, I've been learning a while, so it's possible that my question is very and very stupid. I have a bag of src inside which has another bag of files.

    • The's in the bag of files is a file.txt with an early text,
    • In the src package, MainClass (inside of which is the main method)

    I want to consider the text that's in the file.txt with the help of MainClass and put the text to the console. Google offered me different options, but they didn't find my file. How do I do that? Thank you.



  • Usually J2EE, the annex files don't write themselves inside. The file is either outside the application or the database is used instead of the file. ♪ ♪

    Like if you make a file like the example that Vladimir gave in the commentary.

    public static void write(String fileName, String text) {
        //Определяем файл
        File file = new File(fileName);
    
    try {
        //проверяем, что если файл не существует то создаем его
        if(!file.exists()){
            file.createNewFile();
        }
    
        //PrintWriter обеспечит возможности записи в файл
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());
    
        try {
            //Записываем текст у файл
            out.print(text);
        } finally {
            //После чего мы должны закрыть файл
            //Иначе файл не запишется
            out.close();
        }
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
    

    }

    By summoning the method and pointing out the arguments:

    FileWorker.write("myfile.txt", "my Test Text");

    You'll see he'll be created outside the folder. src Project. Actually, it's in the same folder as it is. src

    It is therefore recommended that folders should be made with resources and that they should be kept outside the project. And indicate the way toward them, that is, by fact, the project that was built (jar For example, the file will be root.

    Either point out the absolute path.

    For an unstructured project, it is possible to indicate the way from the root, that is.

    File file = new File("src/files/file.txt");
    BufferedReader in = new BufferedReader(new FileReader( file.getPath()));
    и т.д.

    But use it to the maximum if it's just for itself and for tests. Not much. Although I don't recommend it. You'd better be human.

    You need to know that after creation, for example jar - folders. src No. So there will be problems with this path) That's where the recommendation was higher.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2