Open text file from with JAR without extracting it - Help please - java

I am trying to open a .txt file saved within a JAR and display its contents in a JTextArea. Below is the code I am trying to use;
URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt");
try {
InputStream stream = urlToDictionary.openStream();
gettysburgTextStrBlder = stream;
System.out.println(stream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I know I am in the correct file location as I have changed the .getResource path around and seen null point exceptions, I have none with the current file path.
The System.out prints the following at runtime:
java.io.BufferedInputStream#3af42ad0
I have also tried;
gettysburgTextStrBlder = String.valueOf(stream);
But the result I get is the same.
I think I am nearly there, but am unsure how to get the actual content of the .txt file and not just the Buffered stream.
Thanks.
Andy

You have to read the content from the inputstream and display in the text area using BufferedReader
URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt");
try {
InputStream stream = urlToDictionary.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
StringBuffer lineContent = new StringBuffer();
while((line = br.readLine()) != null){
lineContent.append(line).append("\n");
}
br.close().
System.out.println(lineContent.toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Related

How to paste data in new line in .data file using java. Currently when i copy paste the contents in .dat file , it comes in one single line

My requirement is to copy the content from one master file and paste it in temp file.
These files are in .dat file format. The code copy paste the contents perfectly but it comes in one single line.
My need is, it should come in new lines instead of one single line.
public static void JavaCopyFile ()
{
try {
FileReader fr = new FileReader("C:\\Automation\\Master_Template.dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("C:\\Automation\\Temp.dat");
String s;
while ((s = br.readLine()) != null) { // read a line
fw.write(s); // write to output file
fw.flush();
}
br.close();
fw.close();
System.out.println("file copied");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please use
writer.write(System.getProperty( "line.separator" ));
to add new line character(s) specific for the OS you use. Also there is no need to flush after each line - one time at the very end is sufficient:
.......
newLine = writer.write(System.getProperty( "line.separator"));
while ((s = br.readLine()) != null) { // read a line
fw.write(s); // write to output file
fw.write(newLine);
}
fw.flush();
.......
Check this link for other solutions:
Create a new line in Java's FileWriter

How to handle FileNotFoundException using try and catch block in Java?

I have written a program in which I am reading a file through the BufferedReader. which file I am reading it may be in .txt format or .csv format.
I want in if file is not available with .txt extension BufferedReader read it with
.csv extension.
I have created a String "FileName" and storing file path on it. and in path variable i have stored file location.
path = "C:\Users\Desktop\folder(1)\"
and I am trying try catch block as follow.
try
{
FileName = path+"abc.txt";
}
catch(Exception e)
{
FileName = path+"abc.csv";
}
BufferedReader BR = new BufferedReader(new FileReader(FileName));
But I am getting java.io.FileNotFoundException.
The exception is thrown in the line BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
So you need the try/catch-block arround this line:
try
{
FileName = path+"abc.txt";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
catch(Exception e)
{
FileName = path+"abc.csv";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
This is the ideal structure for the code:
String filename = null;
try (BufferedReader bundle = null) {
try {
filename = path + "abc.txt";
bundle = new BufferedReader(new FileReader(filename));
} catch(FileNotFoundException e) {
filename = path + "abc.csv";
bundle = new BufferedReader(new FileReader(FileName));
}
// use 'bundle' here
} catch(FileNotFoundException e) {
// log that >>neither<< file could be opened.
}
Notes:
Don't catch Exception. If you do that, you will catch all sorts of unexpected stuff, in addition to the exceptions that you are anticipating.
Use a "try with resource" to ensure that that the reader that was opened is always closed.
You need to get the scoping right ... unless you are prepared to duplicate the code that uses the reader.
Even with the "try again" logic, you still need to deal with the case where all of the filenames that you try fail. AND you need to make sure that the "all fail" case doesn't attempt to use the reader.

JAVA Rewriting in a file

I am trying to rewrite in a file, alongside with the other text in it(not overwrite). But i don't know how can i do it using the exception as my buffered reader lose his initialization.
BufferedReader br;
try {
br = new BufferedReader(new FileReader("file.txt"));
String line ;
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedWriter bw;
try {
File file = new File("file.txt");
bw = new BufferedWriter(new FileWriter("file.txt"));
if(br.readLine() != null) //ERROR Local variable may have not been initialized
bw.newLine();
bw.write("Hello");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileWriter has the ability to set the append flag new FileWriter(file, append)
or if you want to use your version
Initialize the variable with null
BufferedReader br = null;
try with resource may be useful here as well, because it closes everything for you automatically.
Simple. Initialize the variable to null.
Say first line as,
BufferedReader br = null;
...
try {
File file = new File("file.txt");
bw = new BufferedWriter(new FileWriter("file.txt",true));
if(br.readLine() != null) //ERROR Local variable may have not been initialized
...
Try that on for size. That "true" after file.txt means it will append to what file you've found.
Here's a link to the documentation. Take note of the last constructor for FileWriter.
BufferedReader br = null;
To fix your current error changing your first line to this would be how you do it. That reader however is not needed whatsoever.

Change FileWriter to OutputStreamWriter?

How do I convert the FileWriter to OutputStreamWriter? This is the directory that I stored the .java files. src/RX/example.java where RX is the package name. I inserted all the images and text files inside the same directory. Here is my working code with FileWriter.
try {
StringReader stringReader = new StringReader("Save this Message");
BufferedReader bufferedReader = new BufferedReader(stringReader);
FileWriter fileWriter = new FileWriter("src/RX/rxUser.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I actually can go on with this code but in order to work with .jar I have to use the .txt file as a resource. Can someone please alter my code. I am using Netbeans. Thank you.

Read cyrillics and non-cyrillics characters from file java

I have a file with cyrillics and non-cyrillics characters. However, when I read the file the cyrillics characters are not retrived and non-cyrillics characters are retrived. Here is the code I am using
private static String dirToPRocess = "D:\\stopwords_freq_v2.txt";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
dirToPRocess), "UTF-8"));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Are you using eclipse?
You can try the following to get it to work:
save your java file with the character encoding utf-8.
If you want to print cyrillics to the console, I think there might be a setting in eclipse's properties somewhere that does that but not 100% certain- it should print cyrillics by default in my experience.
Your java code looks OK btw.

Categories

Resources