When Grabbing a File through JFileChooser why does this fail? - java

I'm trying to understand Java Swing GUIs. So I created a simple GUI to select a File.
When I attempt to use the FFMPEG wrapper to get file information I get the following error.
java.io.IOException: Cannot run program "C:\File.mp4": CreateProcess error=193, %1 is not a valid Win32 application.
I feel like I'm missing something minor here.
Thanks.
JFileChooser fc = new JFileChooser();
int nReturnVal = fc.showOpenDialog(jPanel1);
File fVideo = null;
try {
if (nReturnVal == JFileChooser.APPROVE_OPTION) {
fVideo = fc.getSelectedFile();
//Now you have your file to do whatever you want to do
jPath.setText(fVideo.getAbsolutePath());
FFprobe ffprobe = new FFprobe(fVideo.getAbsoluteFile().toString());
FFmpegProbeResult probeResult = ffprobe.probe(fVideo.getAbsolutePath());
FFmpegFormat format = probeResult.getFormat();
System.out.format("%nFile: '%s' ; Format: '%s' ; Duration: %.3fs",
format.filename,
format.format_long_name,
format.duration);
jEndTime.setText("" + format.duration);
} else {
//User did not choose a valid file
}
}
catch (Exception ex) {
System.out.println(ex.toString());
}

Related

How to read text and font from .doc using Aspose Word for Java

I have an assignment to read and write to a .doc file and must be able to read the font setting for each word. I'm currently using Aspose word for Java in my development, the write to word and including the font setting to each word is running. The only problem is sometimes when i try to pick a .doc file and read it using the code below, it returns nothing from the System.out.print. But also sometimes it came but with only few words rather than the whole content.
final JFileChooser fc = new JFileChooser();
HomeForm form = new HomeForm();
if (evt.getSource() == jButton2)
{
int returnVal = fc.showOpenDialog(HomeForm.this);
File file = fc.getSelectedFile();
if (returnVal == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "File " +file.getName()+" choosed", "Alert", JOptionPane.CLOSED_OPTION);
jTextField1.setText(file.getName());
String dataDir = file.getPath();
String filename = file.getName();
try {
InputStream in = new FileInputStream(dataDir);
Document doc = new Document(in);
System.out.println(file.getName());;
System.out.println(doc.getText());
in.close();FileInputStream(file.getAbsolutePath());Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);InputStreamReader(fis, Charset.forName("UTF-8"));
} catch (FileNotFoundException ex) {
Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(null, "File choose canceled", "Alert", JOptionPane.CLOSED_OPTION);
}
}
Am i heading toward a right direction by using this code for reading each word and each word font setting? Or maybe Aspose can't handle these kind of processings? Please help, thank you for your time.
You can use Aspose.Words for Java API to get text and Font name of each Run in Document by using the following code:
Document doc = new Document("D:\temp\in.doc");
for(Run run : (Iterable) doc.getChildNodes(NodeType.RUN, true)) {
System.out.println(run.getText());
System.out.println(run.getFont().getName());
}
I work with Aspose as Developer Evangelist.

Installing apk on android device via ADB with Java program on Linux

I am trying to pass a path from Java's inbuilt file manager to ADB with java program on Linux to install apk on android device. When the code is executed the apk selected using file manager never gets installed.
Here is the code:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"APK Files", "apk");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You choose to open this file: " + chooser.getSelectedFile().getName());
File file = new File("");
System.out.println(file.getAbsolutePath().toString());
try {
Process p1 = Runtime.getRuntime().exec("adb kill-server"); //for killing old adb instance
Process p2 = Runtime.getRuntime().exec("adb start-server");
Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\"");
p3.waitFor();
Process p4 = Runtime.getRuntime().exec("adb kill-server");
} catch (Exception e1) {
System.err.println(e1);
}
The following code should install the apk:
Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\"");
I figured it out myself, and here is the code:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String filename = chooser.getSelectedFile().getName();
try {
String[] commands = new String[3];
commands[0] = "adb";
commands[1] = "install";
commands[2] = file.getAbsolutePath();
Process p1 = Runtime.getRuntime().exec(commands, null);
p1.waitFor();
} catch (Exception e1) {
System.err.println(e1);
}
}
Change the line
File file = new File("");
to
File file = chooser.getSelectedFile();
Also, don't forget to check
if(file.exists()) {
to validate the file.
I've spent a week working towards the same task for window system I have found out a simple solution to do this task, Here are some of the following steps that I have applied in my project
The First step is to download the ADB tool (Known as platform-tools) from this URL, and extract the downloaded file into your workspace directory.
Open the directory you downloaded the platform tools into
Create the Batch file if you don't aware how to create batch file follow the following steps
i. Open your text editor notepad or notepad++
ii. Save it as xyz.bat then it will be treated by the window system as a batch file
Open your batch file in your text editor and paste the following command
adb install "b2c.apk" && adb shell am start -n com.xyz.app/com.xyz.b2c.Activity.SplashScreen**
(Here there are two ADB command which separated by the ampersand sign.
The first command is for installing the APK in your Android devices
and the second one is to open the application )
i. b2c.apk is my android APK Which I want to install on my phone
ii. com.xyz.app is an android application package name and com.xyz.b2c.Activity.SplashScreen is an activity package name that I want to open
Save the file and close it, and then copy that file and paste it in the directory with the platform tools. And don't forget to place your APK file in this directory too
cd into the platform directory, and run this Java program:
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestClass {
static int progress = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String ls_str;
Process p = Runtime.getRuntime().exec("cmd /c xyz.bat", null, new File("E:\\Arun_Java_Workspace\\TestApplication\\platform-tools"));
DataInputStream ls_in = new DataInputStream(
p.getInputStream());
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
}
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}

JFileChooser / FileWriter doesn't let me save in root of C: disk

I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!
Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).

Open folder containing file and highlight it

I'm needing to open a folder containing the specified file, and highlight this said file. I have been looking for this for long but I have been unlucky. Could someone explain how this could be done using java?
Would be much appreciated. I am able to open files, folders, but not open the containing folder and highlighting a file. Cross platform code would be a plus, or just point me to the direction! Thanks!
#UPDATE:
Basically I'm doing an image sorter. I have a ArrayList containing filenames, e.g. myarraylist.get(0) would return funny_cat.jpg
This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:
I want the user to be able to open the currently selected item in a JList and open the containing folder with the target file selected.
I would post the code but it is too long and most unnecesary for this question, I will however post below how I open an explorer window, for the settings section of program, in order to choose a new directory to use:
public void browseFolder(){
System.out.println("browsing!");
final JFileChooser fc = new JFileChooser();
File dir = new File(core.Loader.path);
fc.setCurrentDirectory(dir);
// Windows and Mac OSX compatibility code
if (System.getProperty("os.name").startsWith("Mac OS X")) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
fc.setApproveButtonText("Choose directory");
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
// debug
System.out.println("Selected directory for import " + f);
}
}
#UPDATE
I have found the solution, will post as answer below.
So, I just called this method from the action performed and it does the trick.
Basically, the solution was to make this terminal command:
open -R absolute/path/to/file.jpg
This is for Mac OS X only, below is my method I use:
public void openFileInFolder(String filename){
try {
Process ls_proc;
String mvnClean = "open -R " + core.Loader.path + "/" + file_chosen;
String OS = System.getProperty("os.name");
System.out.println("OS is: " + OS);
if (OS.contains("Windows")) {
//code ...
} else {
ls_proc = Runtime.getRuntime().exec(mvnClean);
}
} catch (Exception e){
System.err.println("exception");
}
}

How can I play a WAV file using Java?

I send WAV files using a client and server, but I want to play the WAV when it received. I try this method but it did not work:
Runtime.getRuntime().exec("C:\\Documents and Settings\\Administratore\\Desktop\\gradpro\\test1\\s1.wav") ;
This the exception that I get:
"Error! It didn't work! java.io.IOException: Cannot run program "C:\Documents": CreateProcess error=193, %1 is not a valid Win32 application"
What am I doing wrong?
You need to execute the audio player program (probably windows media player or something similar) and then pass the filename (the full path to the file) in as a parameter:
String wavPlayer = "/path/to/winmediaplayer.exe";
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(wavPlayer, new String[]{fileToPlay}) ;
That should work.
What's wrong with Javas built in WAV playback support? You can play it back using AudioClip:
private void playBackClip(String fileName) {
try {
AudioInputStream soundStream = null;
if (fileName.startsWith("res:")) {
soundStream = AudioSystem.getAudioInputStream(
Object.class.getResourceAsStream(fileName.substring(4)));
} else {
File audioFile = resMap.get(fileName);
soundStream = AudioSystem.getAudioInputStream(audioFile);
}
AudioFormat streamFormat = soundStream.getFormat();
DataLine.Info clipInfo = new DataLine.Info(Clip.class,
streamFormat);
Clip clip = (Clip) AudioSystem.getLine(clipInfo);
soundClip = clip;
clip.open(soundStream);
clip.setLoopPoints(0, -1);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
Is the use of the default audio player mandatory?
If not you might want to look into Java's AudioSystem.
Instead of specifying the media player to use, let windows look it up for you:
String comspec = System.getenv().get("ComSpec");
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(comspec, new String[]{"/c", "start", fileToPlay}) ;
You are basically doing something like:
cmd.exe /c start path_to_wav_file.wav
To see all the options start gives you (start is a built-in operation of cmd.exe, not a stand-alone program, which is why you have to run cmd.exe instead of a 'start.exe'), do
start /h
Old question, but for the record:
java.awt.Desktop.getDesktop().open(new java.io.File(my_filename));
Try:
Runtime.getRuntime().exec("'C:\Documents and Settings\Administratore\Desktop\gradpro\test1\s1.wav'") ;
Note the extra single quotations. I'm not even sure if your method will work, but give that a go.

Categories