Reading Files With Intellij Idea Ide

Reading files with Intellij idea IDE

Just move the file directly to the project folder which calls Java (and something under the blue-blurred stripe you made :P).

If that doesn't help, then move the test123.txt file to FirstJavaProgram directory.

You can also change filename to one of these:

  1. src/test123.txt

  2. FirstJavaProgram/src/test123.txt

I am not sure which one will be fine in your case.

Intellij - Not able to read a file from other package in the same module

Move the file into resources/org/files.

.txt files are not copied to classpath from the source roots by Maven conventions.

If you want to copy these files from the source roots, you need to adjust pom.xml configuration: https://stackoverflow.com/a/23289401/104891.

Eclipse is not following the conventions and you will get different results in command line Maven and in the IDE, which is bad.

Reading text file works in IDE but not in .jar

You need to load the file as a resource. You can use Class.getResourceAsStream or ClassLoader.getResourceAsStream; each will give return an InputStream for the resource.

Once you've got an InputStream, wrap it in an InputStreamReader (specifying the appropriate encoding) to read text from it.

If you need to sometimes read from an arbitrary file and sometimes read from a resource, it's probably best to use separate paths to either create a FileInputStream for the file or one of the methods above for a resource, then do everything else the same way after that.

Here's an example which prints each line from resources/names.txt which should be bundled in the same jar file as the code:

package example;

import java.io.*;
import java.nio.charset.*;

public class Test {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
Test.class.getResourceAsStream("/resources/names.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}

IntelliJ not recognizing a particular file correctly, instead it's stuck as a text file

Please ensure that this file (or a pattern that represents it) is not listed under

SettingsEditorFile TypesText

For OS X

PreferencesEditorFile TypesText

Sometimes the file or pattern are stuck under File type auto-detected by file content instead of Text.



Related Topics



Leave a reply



Submit