Java : reading all files - java

I am attempting to read in files into a java application running via netbeans. I have been successful in previewing the files, but I can only preview .txt files. How can I alter my code to read in any file(s)? (eg. .doc, .docx, .pdf, .jpg, .png).
JFileChooser share = new JFileChooser();
share.showOpenDialog(null);
File f = share.getSelectedFile();
String fileName = f.getAbsolutePath();
try {
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
jTextArea1.read(br, null);
br.close();
jTextArea1.requestFocus();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}

you should use something like apache tika
http://tika.apache.org/
this will allow you to read almost any kind of file
also have a look at java.io.File.list() to find out the types of files you have at a location

You can read them alright ; it's just that they are huge blobs of binary data you can't make any sense of without the appropriate tools. Open one of them with a notepad and you'll get what I'm saying.
Their associated software (Word, Reader, etc...) usually do the decoding, but you may find java libraries that can do as much.

Related

Reading and displaying large formatted text documents in Android

I'm developing an Android app which is supposed to present large text files (books for example), for the user to browse, read, and search.
My question is as follows:
How should I read and present the text file, which is currently in either a PDF or Word format, and is formatted?
What file should the text be in (.doc, .txt, .xml, .html)?
What controls/elements and code should I use to read it on the app so that it should be presented efficiently and formatted correctly (TextView, WebView, PDF reader, or some other way)?
Thanks.
It really depends on your application and programming skills,
Grabbing texts from PDFs, word files, etc.. can be done using
libraries (lots are available)
you can save your files as raw text files (they could be readable
manually) if you want to want to secure it you can encrypt it before
saving and you can save with custom extension( .lib,.abc etc..).
TextViews are the easiest as you can change the colors ,
fonts and text size, it's really fast and easy to deal with.
Edit : example of reading a text file
File myFile = new File("/sdcard/filename.txt");
FileInputStream iStr = new FileInputStream(myFile);
BufferedReader fileReader = new BufferedReader(new InputStreamReader(iStr ));
String TextLine= "";
String TextBuffer = "";
while ((TextLine= fileReader.readLine()) != null) {
TextBuffer += TextLine+ "\n";
}
textView1.setText(TextBuffer );
fileReader.close();
example of writing a text file :
File myFile = new File("/sdcard/filename.txt");
myFile.createNewFile();
FileOutputStream oStr = new FileOutputStream(myFile);
OutputStreamWriter fileWriter= new OutputStreamWriter(oStr);
fileWriter.append(textView1.getText());
fileWriter.close();
fOut.close();

Java - Errors when using .txt files in .jar

When I try and load up a .txt file in my code, I get this error:
java.io.FileNotFoundException: file:\C:\Users\Me\Desktop\Program.jar!\test\foo.txt (The filename, directory name, or volume label syntax is incorrect)
My code for loading these files is this:
try {
String path = getClass().getResource(file).getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
...
} catch(IOException e) {
System.err.println("Could not read file!");
e.printStackTrace();
System.exit(-1);
}
And the string I load into the method is this:
foo.txt
Even though I've checked many times, the file exists in that exact path, yet my program still can't find it. And why is there an exclamation mark at the end of Program.jar? Is it important?
Thank you to anyone who helped answer my questions.
If you launch it out of jar in console, you better access your resource as a InputStream and process it the desired way. When you enter the actual path(especially not relative) - you are trying to get to the file that is INSIDE the jar, which is wrong.
Here's close (pseudo) code for your problem:
InputStream resource = ClassName.class.getResourceAsStream("/test/foo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource));
//do some stuff
resource.close();
reader.close();
The exclamation mark is a separator the JVM uses to note the .jar file in the path.

Java Applet Output File

I am trying to create a Java Applet that outputs information to a text file located in the same directory as the java applet. I understand Java Applets are not ideal, but I have spent a great deal of time on this and if possible want to solve this through applets. Here is some of my code on how I could read code from a file into a text box. I assume it would be something similar to this, but outputted.
public void readFile() {
String line;
URL url = null;
try {
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e) {
}
try {
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "\n");
}
a1.append("File Name : " + fileToRead + "\n");
a1.append(strBuff.toString());
}
catch(IOException e) {
e.printStackTrace();
}
}
If you want an applet to store data on the local machine, from 6u10 the javax.jnlp.PersistenceService is available.
or on your local machine...
java.io.File file = new java.io.File(System.getProperty("user.home"), "yourfile.txt");
You must have it signed, otherwise...
Keep in mind that from an Applet, you cannot directly write to the server's file system. You can issue a request to the server that causes the server to write to its own file system, but an Applet does not have a way to write to a file system on a remote machine.
A signed Applet has every right to write to the local file system of the person running the Applet. If you are writing to the "current directory" (rather than an absolute full path), then make sure you know what directory the Applet is running in. Otherwise you may indeed create a file, but not be able to find it!
EDIT
Signed Applet Tutorial

How to use the .txt, .xml and .properties file inside the executable jar?

I have a java project which will read a txt file and process that.
For production purpose, I will need to generate an executable jar which contains this txt file.
I use the code like:
BufferedReader br = new BufferedReader(new FileReader("src/txt_src/sample.txt"));
My jar contains txt_src/sample.txt, but can't use it. Instead, if I put a src directory which has src/txt_src/sample.txt structure, the jar works.
It will be better to generate directly by Eclipse.
Thanks in advance!
Treat the file as a resource and give the path as the package hierarchy.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29
You can then take the InputStream and wrap it in an InputStreamReader that is wrapped in a BufferedReader. Wrap it in a BufferedInputStream if you need to define the encoding, which you should do.
new BufferedReader(new InputStreamReader(new BufferedInputStream(this.getResourceAsStream("myPackage/myFile.txt")), "UTF-8"));
Put your files in the assets Folder of your Project and use them with:
InputStream stream = null;
try {
stream = getAssets().open("sample.txt");
}
catch (IOException e) {
e.printStackTrace();
}

Embed .jar file in html that require .txt file (java)

I'm using the acm libraries for my Java program, and I want to embed my program into my website via HTML. I have other .jar files embedded just fine in my website, by using the
<applet archive="file.jar, acm.jar"
code="main.class"
width=400 height=600 />
but have found that when embedded in HTML the program sort of freaks out and stops responding when it gets to the part where it should load the .txt file.
I remember vaguely my AP CompSci teacher telling us that java in web browsers blocked the import of .txt files, but I might be remembering incorrectly. Here is my java code below:
public NameSurferDataBase(String filename) {
nameEntry = new HashMap<String, NameSurferEntry>();
try {
BufferedReader rd = new BufferedReader(new FileReader(filename));
while (true) {
String line = rd.readLine();
if (line == null) break;
NameSurferEntry entry = new NameSurferEntry(line);
nameEntry.put(entry.getName().toUpperCase(), entry);
}
} catch (IOException ex) {
throw new ErrorException(ex);
}
}
So not only do I not know how to actually add the .txt file as something to use before it runs, I don't even know if it is possible.
It's because when running applets, the security manager doesn't let you work with the filesystem (unless you specifically change the plugin settings which is a bad idea). If you're just trying to read, put the file in your classpath, and use ClassLoader.getResourceAsStream(String resource) to get the input stream instead.

Categories