Open any file from within a java program - java

Opening files in java seems a bit tricky -- for .txt files one must use a File object in conjunction with a Scanner or BufferedReader object -- for image IO, one must use an ImageIcon class -- and if one is to literally open a .txt document (akin to double-clicking the application) from java, this code seems to work:
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("notepad Text.txt");
}
}
I'm not positive, but I think other file-types / names can be substituted in the parenthesis after exec -- anyway, I plan on opening certain files in a JFileChooser when the user clicks on a file to open (when the user clicks on a file, the path to the file can be obtained with the getSelectedFile() method). Though I'm more specifically looking to be able to open an Arduino file in the Arduino IDE from a java program, like a simulated double-click.. perhaps something like this?
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("Arduino C:\\Arduino\\fibonacci_light\\fibonacci_light.ino");
}
}
A point in the right direction would be appreciated.

Have you tried this? If there is a registered program for your file in windows, this should work. (i.e. the default application should open the file)
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
The file parameter is a File object.
Link to API
Link to use cases and implementation example of the Desktop class

This is what I do in my projects using java.awt.Desktop
import java.awt.Desktop;
import java.io.IOException;
import java.io.File;
public class Main
{
public static void main(String[] args) {
try {
Desktop.getDesktop().open(new File("C:\\Users\\Hamza\\Desktop\\image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

How do I create those methods correctly for a html file?

Completely new to programming and studying it right now at a university. This might seem easy but they literally showed us nothing on how to program so this task is hard for me to do. So maybe someone here can help me understand how I can do this:
The task:
Create a method called "open(String fileName)" that creates and opens a text file with the name fileName
Create a method called "pageStart()" that writes "html" into the file
There are a lot more methods I have to create but all of them should be easy if I understand how the "pageStart()" one works.
package exporter;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class HTMLCreator {
public static void main(String[] args) {
open("Hello.txt");
}
public static void open(String fileName) {
File file = new File(fileName);
try {
// Creates new file
if (file.createNewFile()) {
}
// Opens file
Desktop desktop = Desktop.getDesktop();
if (file.exists())
desktop.open(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Ok so that does create a .txt file and opens it. So far so good.
Now the problem. I have to create a method that WRITES into that .txt file and I have NO clue how to do that.
What I tried until now:
public static void startPage() {
FileWriter fw = new FileWriter(file)/*<-- obviously won't work but I don't know how it would work...*/;
fw.write("<html>");
fw.close();
}
I know that this obviously won't work since the file that I want is not in that method. How do I do that?
How do I make it so my startPage() method writes into the Hello.txt file I created earlier?
I would appreciate help a lot!!!
My question is not about how to create and write into a textfile! My question is more how you combine two methods to do this! It would help immensely if someone could write two methods for me, one that creates and opens a textfile and another method that writes into the textfile that the first method created and opened. That would most likely solve my problem!

ProcessBuilder call another java file same package

I am learning how to use ProcessBuilder, I created a package called socketspractice, inside I have 2 classes, I am trying to create a new process where 'Program.java' calls 'test1.java' so it prints 'test1'.
When I use command prompt: "java socketspractice.test1" 'test1' prints, but using Netbeans it doesn't.
The question is, how can I set the path so it works the same way or what else am I missing? I am using Netbeans for this.
Program.java
package socketspractice;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder;
public class Program {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builderExecute = new ProcessBuilder("java", "socketspractice.test1");
builderExecute.start();
}
}
AND
test1.java
package socketspractice;
public class test1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("test1");
}
}
The main issue with ur approach is that when you are starting ProcessBuilder it doesnt know where ur project lies on your machine, because its running as a seperate JVM process.
So please create you project as a maven project and then try to put the compiled jar in classpath and then start the process builder.
ProcessBuilder pb = new ProcessBuilder("java","-classpath",
"<complete location of your jar containing test1>", "socketspractice.test1")

Eclipse not finding file?

I am using eclipse and I have my text file in the correct directory (src folder). I just want to read the file and count all the words in it. For some reason I am getting a file not found exception being thrown.
here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester {
public static int getSizeOfDictionary(File dictionary)
throws FileNotFoundException {
int count = 0;
Scanner reader = new Scanner(dictionary);
while (reader.hasNextLine()) {
reader.nextLine();
count++;
}
reader.close();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
File test = new File("words.txt");
System.out.println(getSizeOfDictionary(test));
}
}
You could use this.getClass().getResource("words.txt") which will find that file on the current classpath.
From the main method you could use: Tester.class.getResource("words.txt")
when eclipse launches jvm it sets current directory to project base directory generally (unless you modify the default current directory)
${workspace_loc}/project_name
so you need to change your File initialization to
File test = new File("src/words.txt");
Note:
It will just be limited to this project structure, if you export it to jar it will not work any more, I assume you just need it as part of exercise
You have to use property class to access your file within class-path and source folder
you can try like:
this.getClass().getResourceAsFile("words.txt")

Jar Maker -- Which is the main class?

Alrighty, so I'm working on making a .jar for a client for a little game and I know how to use everything and have done this before, on windows, now i'm on a mac. This shouldn't make a difference but incase you wanted to know, there you go.
Now, I have a folder in eclipse named client, now normally the client.java is the main class but there is another named EGUI, this has the "public static void main(String[] args)", but in my client.java file, it also has a method like this:
public static final void main(String args[])
{
try
{
anInt957 = 0;
anInt958 = 0;
method52(false);//highmem
aBoolean959 = true;//members
signlink.storeid = 32;
signlink.startpriv(InetAddress.getLocalHost());
client client1 = new client();
client1.method1(503, false, 765);
setserver(args[0], "5555");
return;
}
catch(Exception exception)
{
return;
}
}
I guess my question is, does the "final" make it the main file? Or would it still be the EGUI, which looks like this:
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class EGUI
{
public static void main(String args[])
{
client.main(new String[] {
"127.0.0.1", "127.0.0.1", "127.0.0.1"
});
}
}
So, what i'm asking for is, why is it that when I'm setting the main file to EGUI, it isnt working? the applet opens up, but I keep getting an "error connecting to server" message every time, when I run it through terminal by copying the run.bat info and pasting that, it works perfectly! Any help is greatly appreciated!
public static void main(String args[]) means you can execute the class from the commandline. The final keyword means the method cannot be overridden by a sub class.
In your case this does not make it the jar's main execution class. The main class is set in META-INF/MANIFEST.MF. Normally it should have a line:
Main-Class: classname
but then with the actual class.
So open the jar with a zip program, and check MANIFEST.MF.
Your client.java has a main method, for testing purposes I suppose.

Java Swing - How to double click a project file on Mac to open my application and load the file?

I have created a Mac Java Swing application, and i have set a file extension(*.pkkt) for it in the "Info.plist" file, so when double clicking that file it opens my application.
When i do that the program runs fine. Now i need to load the (*.pkkt) project in the program, but the file path is not passed as an argument to the main(...) method in Mac as happens in Windows Operating System.
After some search i found an Apple handling jar "MRJToolkitStubs" that has the MRJOpenDocumentHandler interface to handle such clicked files. I have tried using it to load that file by implementing that Interface in the main program class, but it is not working. The implemented method is never called at the program start-up.
How does this Interface run ?
------------------------------------------------- Edit: Add a Code Sample
Here is the code i am using :
public static void main( final String[] args ) {
.
.
.
MacOpenHandler macOpenHandler = new MacOpenHandler();
String projectFilePath = macOpenHandler.getProjectFilePath(); // Always Empty !!
}
class MacOpenHandler implements MRJOpenDocumentHandler {
private String projectFilePath = "";
public MacOpenHandler () {
com.apple.mrj.MRJApplicationUtils.registerOpenDocumentHandler(this) ;
}
#Override
public void handleOpenFile( File projectFile ) {
try {
if( projectFile != null ) {
projectFilePath = projectFile.getCanonicalPath();
System.out.println( projectFilePath ); // Prints the path fine.
}
} catch (IOException e) {}
}
public String getProjectFilePath() {
return projectFilePath;
}
}
As mentioned in the comment above "getProjectFilePath()" is always Empty !
On Java 9, use Desktop.setOpenFileHandler()
The proprietary com.apple.eawt packages have been removed from recent versions of Java and has been incorporated into various methods in the Desktop class. For your specific example:
import java.awt.desktop.OpenFilesHandler;
import java.awt.desktop.OpenFilesEvent;
import java.io.File;
import java.util.List;
public class MyOpenFileHandler implements OpenFilesHandler {
#Override
public void openFiles​(OpenFilesEvent e) {
for (File file: e.getFiles​()) {
// Do whatever
}
}
}
Then elsewhere, add this:
Desktop.getDesktop().setOpenFileHandler(new MyOpenFileHandler());
The OpenFilesEvent class also has a getSearchTerm() method. Say that a person used Spotlight on macOS to search for the word "StackOverflow", then decided to open up a document. With this method, can you determine that "StackOverflow" was the word they searched for, and choose to do something with that (perhaps highlight the first occurrence of the word).
You're going to want to use the Apple Java Extensions.
They should be included in any JDK that runs on Mac OS X, but the documentation is kind of hard to get. See this answer for more details.
Specifically, you'll want to make an OpenFilesHandeler.
This code snippet should work:
import com.apple.eawt.event.OpenFilesHandeler;
import com.apple.eawt.event.AppEvent;
import java.io.File;
import java.util.List;
class MacOpenHandler implements OpenFilesHandeler {
#Override
public void openFiles(AppEvent.OpenFilesEvent e) {
List<File> files = e.getFiles();
// do something
}
}
And somewhere:
import com.apple.eawt.Application;
...
MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);

Categories