Open a local PDF document at an arbitrary page using java - java

As the title says, I have a PDF document which is stored locally and using Java I would like to open it on an arbitrary page. My question is much the same as this question, however the proposed solution seems rather hacky so I would prefer a more conventional answer if possible. I understand that the code shown below will not work because #page=5 should be appended to the URL in the browser and not the file path, however I'm really not sure what to try next. Any help would be much appreciated!
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class OpenPdfTest {
public OpenPdfTest(){
try {
File myFile = new File("test.pdf");
URL url = myFile.toURI().toURL();
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url + "#page=5");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
new OpenPdfTest();
}
}

What about using http://tika.apache.org/ and read the whole file, convert it and use the part of the pdf File that you want. You can read in any File you want with Apache Tika. With this Lib you can open any kind of files, also pdf-Files and proceed them.
Take my Answer just as a first guess.

Related

I want to read contains methods, in a .java file as below,

As an example, I have a .Java file like this,
public class A {
private void callData() {
//There can be custom methods like this
checkImage("A",true);
checkObject("B","C",true);
}
}
I want to read this methods name and parameters. I dont need to go inside those methods and take the values but I want to take the name and parameters. This A.java is a file located in my machine. Now I want to write a code to read this method names and parameters. I think this is clear :)
Thank you
Most questions should contain where possible a minimal example of things you have already tried as it helps us answers the question more efficiently in the problem you are having with your code. Anyway for picking out method headers and parameters you should probably be looking into using a regex if you dont want a more fully complete solution for code parsing:
Firstly read your file in, you can see examples for different version of java here from #Grimy:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public String readFile(String filename)
{
String content = null;
File file = new File(filename); //for ex foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){reader.close();}
}
return content;
}
Then theres a number of solutions for a possible regex you could use here and here
(?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)*
Once you have designed a regex you could use any of the normal ways to group the matches and output what you need from the matches.
Its worth mentioning for this type of program solutions such as ANTLR can be useful (but overkill, thenless you are looking to extend beyond just method headers) as they can generate an entire parser for you to use.

Downloading HTML instead of File

I'm using Java code to download a file from the Internet and save it to some directory.
However, the code downloads the HTML source code of the page instead of the file contents.
The code below illustrates the problem:
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class JavaFileDownloadTest
{
public static void download(String remoteURL, String targetFilePath)
throws IOException
{
URL downloadableFile = new URL(remoteURL);
ReadableByteChannel readableByteChannel = Channels.newChannel(downloadableFile.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath);
fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
}
public static void main(String[] arguments) throws IOException
{
String userHome = System.getProperty("user.home");
String fileName = "Test.txt";
String targetFilePath = userHome + File.separator + "Downloads" + File.separator + fileName;
download("http://bullywiiplaza.cuccfree.com/" + fileName, targetFilePath);
Desktop.getDesktop().open(new File(targetFilePath));
}
}
The file located here contains the text
Hello StackOverflow!
However, when downloaded using the above code, I'm getting the HTML source code as file content instead:
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("ae71113e4baf38cee1c1aacf0ae66c00");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; document.cookie="referrer="+escape(document.referrer); location.href="http://bullywiiplaza.cuccfree.com/Test.txt?ckattempt=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
Why is this and how do I fix it? I already tried various libraries and methods for downloading files but all of them yielded this same "faulty" result.
I think the target url executes some javascript to provide the file. This script has to be interpreted (and executed) by some javascript engine.
So you need either some resolution to get the real file url (and not just the javascript) or integrate some javascript engine to execute the script code and get the result.
I think this could help you: Executing javascript in java - Opening a URL and getting links
or better:
http://www.java2s.com/Code/Java/JDK-6/ExecuteJavascriptscriptinafile.htm
I switched the website hoster to this one and now the code from above works as expected.
http://bullywiiplaza.cuccfree.com/Test.txt doesn't exist. I think the url should be https://bullywiiplaza.cuccfree.com/Test.txt which exists.

Java File Reader not finding appropriate file

I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.

Save information from Java application [duplicate]

This question already has answers here:
What is the proper way to store app's conf data in Java?
(6 answers)
Closed 9 years ago.
I'm making an application using databases in Java (compiled as JAR). In order to connect to the database, the user must enter the database's address. It would be a pain to remember/type the address every time you want to use the program.
Thus, I want to save the address to a text file somewhere...but where? I want this application to be accessible to anyone on any operating system, and I'd prefer not to have my JAR in a folder.
Is it possible, maybe, to write/read from a text file located within the JAR itself?
Like Sotirios Delimanolis said you can create and save a properties file.
It is very simple to do it please have a look at the example below (see the original the post)
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WritePropertiesFile {
public static void main(String[] args) {
try {
Properties properties = new Properties();
properties.setProperty("favoriteAnimal", "marmot");
properties.setProperty("favoriteContinent", "Antarctica");
properties.setProperty("favoritePerson", "Nicole");
File file = new File("test2.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Favorite Things");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I would not suggest you save the properties file into the jar file however it is possible to do so.
Please follow the stackoverflow answer at: how to write into a text file in Java
You can open a file anywhere in your jar using e.g. ClassLoader.getResourceAsStream()
Here's what worked for me. I simply used the path System.getProperty("user.home") as my file's location. This is operating system neutral.
Try the Java Preferences API to store user data like this.
Storing data in the application folder will be problematic (e.g., user might not have permission, application might be signed, etc). You can store a file in the user home directory, but most operating systems have a designated location to store user data (e.g., 'Application Support' on Mac, AppData on Windows, etc). Plus the user probably won't appreciate you cluttering up their home directory. You can create a properties file and handle storing it in the proper place yourself, but an easier solution would be to use the Preferences API which abstracts the pain of having to know where to write the file.
Here is an example:
import java.util.prefs.Preferences;
public class Test {
public static final String DB_PROP = "user.selected.db.address";
public static void main(String[] args) {
Preferences prefs = Preferences.userNodeForPackage(Test.class);
prefs.put(DB_PROP, "foo");
String dbAddress = prefs.get(DB_PROP, null);
System.out.println(dbAddress);
}
}

Using Java unable to save to text file

I'm trying to get my submit button to save the GUI in a text file, I've made the GUI and the button listener ...etc but I'm having trouble making the method that saves the information from the GUI into a text file.
so far i have:
public void save() {
File k1 = new File("documents/"+"newfile.txt");
try {
k1.createNewFile();
FileWriter kwriter = new FileWriter(k1);
BufferedWriter bwriter = new BufferedWriter(kwriter);
bwriter.write(txtField1.getText().trim());
bwriter.newLine();
bwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
but it doesn't seem to work, nothing happens; is there anything I'm missing?
You're file is called .txt - perhaps insert a name in the first row:
File k1 = new File("documents/filename.txt");
You should be getting an error when running that code.
The problem is that the document directory doesn't exist or it is not where you expected.
You can check for the parent directory with:
if(!k1.getParentFile().exists()){
k1.getParentFile().mkdirs();
}
Alternatively you need to set the file to be a more precise location.
org.apache.commons.lang.SystemUtils might be able to help you out here with user home.
i was just think is there a easier way, for example i already have the Jfilechoser open a "save as box" when the "submit" button is pressed so is there a easier way to create the file (saving the gui infomation in a txt file) ?
This is a continuation on your previous question. You should just get the selected file and write to it with help of any Writer, like PrintWriter.
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println(txtField1.getText().trim());
writer.flush();
} finally {
writer.close();
}
Don't overcomplicate by creating a new File() on a different location and calling File#createFile(). Just writing to it is sufficient.
See also:
Java IO tutorial
update here's an SSCCE, you can just copy'n'paste'n'compile'n'run it.
package com.example;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) throws IOException {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println("Hello");
writer.flush();
} finally {
writer.close();
}
Desktop.getDesktop().open(file);
}
}
}
My guess is that the file is being created, but not in the directory that you expect. Check the value of the user.dir system property and see what it shows. This is the current working directory of your JVM.
You may need to either:
Specify a full path in the code (as Martin suggested), e.g. new File("/home/foo/newfile.txt")
Change the working directory of the JVM. The way that you do this depends on how you are launching it (e.g. if you are running the java command directly from a CLI, then just switch directories first, if you are running from an IDE then change the launch configuration, etc.).
As far as I know, you cannot change the working directory at runtime (see this SO question).
Your code is working for me with minor change.
As a debugging process, I would completely delete the directory path and try to use a file only..
instead of
File k1 = new File("documents/"+"newfile.txt");
use
File k1 = new File("newfile.txt");
Check where your file is generated and then create directory there..
Good luck!!

Categories

Resources