Read text file from resource folder and populate jTextArea (NetBeans Java) - java

StringBuilder result = new StringBuilder("");
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("DBase.dat").getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
jTextArea1.setText(result.toString());
scanner.close();
} catch (FileNotFoundException ex) {
}
I am new to JAVA and netBeans I am using this code to read a text file from resources folder and then populate jTextArea from that file. But I am getting Errors. I want to read textfile line by line not all the text at once...
Please Help me what should I do.
I am pasting a picture too...
Project Picture

try something like that:
File file = new File(classLoader.getResource("DBase.dat").getPath());

Related

NoSuchFileException while running jar file

When we convert code to jar file we get this error.
the code works with IDE
public String getwordleString() {
Path path = Paths.get("..\\termproject\\word_database.txt");
List<String> wordList = new ArrayList<>();
try {
wordList = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}
Random random = new Random();
int position = random.nextInt(wordList.size());
return wordList.get(position).trim().toUpperCase();
}
Error part is : https://ibb.co/z6vZLW5
Using Paths.get("..\\termproject\\word_database.txt") assumes that there is a directory "..\termproject\word_database.txt" starting at the current working directory. If the file does not exist, you will get an error.
If you want to wrap the directory with the JAR, you can set you "termproject" file as a src or class file. Then this will be accessible via getClass().getResourceAsStream("/word_database.txt"). Now you can read the text from the file with a BufferedReader like so:
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/word_database.txt")));
String data = reader.lines().collect(Collectors.joining("\n"));

Can't read from my src/main/resources directory

I'm trying to learn more about how to read files in Java.
Currently I have some code that will read a file from the same directory:
File file = new File(getClass().getResource(fileName).getPath());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
My issue is when I try to move my file into the resources directory.
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
I can read the file from the resources directory with an InputStream, but I'm trying to avoid doing that way. The file variable is what I would expect to work, but it doesn't.
Does anyone have advice on where I should go from here?
File file = new File(getClass().getResource("/"+fileName).getFile());
if the file is at the root of src/main/resources folder and you use Maven.
This is how I ended up solving this issue:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("main/resources/" + fileName).getFile());
Could you try the following?
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());

Examining file structure in application jar

I have a directory in my jar called "lessons". Inside this directory there are x number of lesson text files. I want to loop through all these lessons read their data.
I of course know how to read a file with an exact path:
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/lesson1.lsn")));
try{
in.readLine();
}catch(IOException e){
e.printStackTrace();
}
But what I want is something more like this:
File f = new File(Main.class.getResource("lessons"));
String fnames[] = f.list();
for(String fname : fnames){
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/" + fname)));
in.readLine();
}
File however doesn't take a URL in it's constructor, so that code doesn't work.
I will use junit.jar in my test as an example
String url = Test1.class.getResource("/org/junit").toString();
produces
jar:file:/D:/repository/junit/junit/4.11/junit-4.11.jar!/org/junit
lets extract jar path
String path = url.replaceAll("jar:file:/(.*)!.*", "$1");
it is
D:/repository/junit/junit/4.11/junit-4.11.jar
now we can open it as JarFile and read it
JarFile jarFile = new JarFile(path);
...

How to read from a file not in Eclipse in Java

I have a file which is needed for running tests - this file needs to be personalized (name and password) by whomever is running the test. I do not want to store this file in Eclipse (since it would need to be changed by whomever runs the test; also it would be storing personal info in the repo), so I have it in my home folder (/home/conrad/ssl.properties). How can I point my program to this file?
I've tried:
InputStream sslConfigStream = MyClass.class
.getClassLoader()
.getResourceAsStream("/home/" + name + "/ssl.properties");
I've also tried:
MyClass.class.getClassLoader();
InputStream sslConfigStream = ClassLoader
.getSystemResourceAsStream("/home/" + name + "/ssl.properties");
Both of these give me a RuntimeException because the sslConfigStream is null. Any help is appreciated!
Use a FileInputStream to read data from a file. The constructor takes a string path (or a File object, which encapsulates string path).
Note 1: A "resource" is a file which is in the classpath (alongside your java/class files). Since you don't want to store your file as a resource because you don't want it in your repo, ClassLoader.getSystemResourceAsStream() is not what you want.
Note 2: You should use a cross-platform way of getting a file in a home directory, as follows:
File homeDir = new File(System.getProperty("user.home"));
File propertiesFile = new File(homeDir, "ssl.properties");
InputStream sslConfigStream = new FileInputStream("/home/" + name + "/ssl.properties")
You can simplify your work, using Java's 7 method:
public static void main(String[] args) {
String fileName = "/path/to/your/file/ssl.properties";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also improve your way of reading properties file, using Properties class and forget about reading and parsing your .properties file:
http://www.mkyong.com/java/java-properties-file-examples/
Is this a graphics program (ie. using the Swing library)? If so it is a pretty simple task of using a JFileChooser.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html
JFileChooser f = new JFileChooser();
int rval = f.showOpenDialog(this);
if (rval == JFileChooser.APPROVE_OPTION) {
// Do something with file called f
}
You can also use Scanner to read the file.
String fileContent = "";
try {
Scanner scan = new Scanner(
new File( System.getProperty("user.home")+"/ssl.properties" ));
while(scan.hasNextLine()) {
fileContent += scan.nextLine();
}
scan.close();
} catch(FileNotFoundException e) {
}

Reading a txt file in a Java GUI

All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file, but how do I get the entire file into a string? Also, does the txt file go in the src folder in Eclipse?
This code to display the selected file contents in you Jtext area
static void readin(String fn, JTextComponent pane)
{
try
{
FileReader fr = new FileReader(fn);
pane.read(fr, null);
fr.close();
}
catch (IOException e)
{
System.err.println(e);
}
}
To choose the file
String cwd = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(cwd);
JButton filebutton = new JButton("Choose");
filebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (jfc.showOpenDialog(frame) !=JFileChooser.APPROVE_OPTION)
return;
File f = jfc.getSelectedFile();
readin(f.toString(), textpane);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setCursor(Cursor.
getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
});
}
});
All I want to do is display the entire contents of a txt file. How
would I go about doing this? I'm assuming that I will set the text of
a JLabel to be a string that contains the entire file but how do I get the entire file into a string?
You would be better of using a JTextArea to do this. You can also look at the read() method.
does the txt file go in the src folder in Eclipse?
Nope. You can read files from any where. The tutorial on "Reading, Writing, and Creating Files" would be a good place to start
create text file in your project's working folder
read your text file line by line
store the line contents in stringBuilder variable
then append next line contents to stringBuilder variable
then assign the content of your StringBuilder variable to the JLabel's text property
But it is not good idea to store whole file's data into JLabel, use JTextArea or any other text containers.
Read your file like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
now assign value of everything to JLabel or JTextArea
JLabel1.text=everything;
Use java.io to open a file stream.
Read content from file by lines or bytes.
Append content to StringBuilder or StringBuffer
Set StringBuilder or StringBuffer to JLable.text.
But I recommend using JTextArea..
You don't need to put this file in src folder.

Categories