I am studying for the Java 1.8 OCP exam and I ran across something in the Oracle study guide p.459 where it says you can load a remote URL as a FileSystem object. I tried this and can't get it to work. What is the simplest hello-world style answer to get this working?
import java.net.*;
import java.nio.file.*;
public class FileTest {
public static void main(String[] args) throws URISyntaxException, MalformedURLException {
FileSystem remoteFS = FileSystems.getFileSystem(
new URI("http://www.gutenberg.org/files/55007")
);
Path remotePath = remoteFS.getPath("55007-0.txt");
System.out.println(remotePath.isAbsolute());
}
}
It throws the error:
Exception in thread "main" java.nio.file.ProviderNotFoundException:
Provider "http" not found
at java.nio.file.FileSystems.getFileSystem(FileSystems.java:224)
at qa.test.FileTest.main(FileTest.java:7)
Addendum:
FileSystemProvider.installedProviders() returns
[sun.nio.fs.MacOSXFileSystemProvider#4554617c, com.sun.nio.zipfs.ZipFileSystemProvider#74a14482]
Related
I'm trying to pass a file from the main method to another class that should handle it, but while the file is recognized in the main class, it throws this error in the second one.
Exception in thread "main" java.io.FileNotFoundException: file:/home/giovanni/Desktop/spring-course/exercises-part2/word-inspection/target/classes/words.txt (File o directory non esistente)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at com.vanny96.WordInspection.<init>(WordInspection.java:16)
at com.vanny96.App.main(App.java:13)
The path for the file is correct, and the file is there, so I have no idea why it isn't working.
I tried looking around for a solution but couldn't find any, and the fact that the file works fine in the main method while not in another one confused me a lot, if you could point me to a thread where this is solved it would be enough!
Here is the code:
Main App
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
public class App {
public static void main(String[] args) throws FileNotFoundException
{
URL fileUrl = App.class.getClassLoader().getResource("words.txt");
File file = new File(fileUrl.toString());
WordInspection inspector = new WordInspection(file);
}
}
WordInspection class
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordInspection {
private File file;
private Scanner reader;
public WordInspection(File file) throws FileNotFoundException {
this.file = file;
this.reader = new Scanner(this.file);
}
}
I think the Scanner is not able to resolve the file as an URL, but is able to resolve it as an URI.
If you change the line:
File file = new File(fileUrl.toString());
to
File file = new File(fileUrl.toURI());
your Scanner should be able to resolve the file (i have tested it). You will have to add an additional throws class for the toUri() method.
I need to open a video in the VLC Player with Java. I have created this program but I don't know how to run a video with this pre-existing code, what should I add in it?
Currently I am using:
package vlc.player;
import java.io.*;
public class vlc
{
public static void main(String[] args) throws IOException,
InterruptedException
{
Runtime.getRuntime().exec("\"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe\"");
System.out.println("VLC started.");
}
}
Reading the doc you can start VLC with an embedded HTTP server: https://wiki.videolan.org/Documentation:Advanced_Use_of_VLC/#The_HTTP_interface
And the send HTTP requests to perform some operations:
https://wiki.videolan.org/VLC_HTTP_requests/
If you only want to play a file once, just start it as
vlc.exe file://c:\\path\\file.avi
package vlc.player;
import java.io.*;
public class vlc {
public static void main(String[] args)
throws IOException, InterruptedException
{
String [] s= new String[]
{"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe","D:\\Video\\3G\\K.MP4"};
Runtime.getRuntime().exec(s);
System.out.println("VLC started."+"prashant.ibmce#gmail.com");
}
}
I tried to to include an exe-file into a jar-Application and to run it. The idea is to extract it temporary at first and then to run the temp-exe-file. How to do that? That is what I have tried. There is my code. It occurs the exception java.io.FileNotFoundException because of the source file "ffmpeg.exe". I verified, but the file is included and the directory is correct.
package extractffmpeg;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
public class ExtractFFmpeg extends Application {
public void start(Stage primaryStage) throws IOException, URISyntaxException {
extractExe();
System.out.println("extract successfull");
Platform.exit();
}
public static void main(String[] args) {
launch(args);
}
public void extractExe() throws URISyntaxException, IOException{
final String resourcesPath = "ffmpeg/ffmpeg.exe";
URL url = ExtractFFmpeg.class.getResource(resourcesPath);
File source = new File(url.toString());
System.out.println("shows url of ffmpeg: " + url.getPath());
System.out.println("shows file of ffmpeg: " + source);
File destination = new File("C:/Users/FNI2Abt/Desktop/ffmpeg.exe");
FileUtils.copyFile(source, destination);
}
}
The idea is to create a self-extracting archive. The archive shall contain both JAR and EXE. The JAR file shall contain a class which would call Process.exec(...) on the adjacent EXE. Starting there, you can follow this tutorial:
How do I make a self extract and running installer
I am trying to test some data mining algorithms from smile project (https://github.com/haifengl/smile). The testing process is simple (I have included into existing Eclipse project Maven repositories of Smile project), but with the following code I catch a NPE (Null pointer exception) with InputStream , the file is just heavy csv file necessary to be read (included in the same project folder)
package com.algorithms;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import smile.data.AttributeDataset;
import smile.data.NominalAttribute;
import smile.data.parser.DelimitedTextParser;
public class DenclueTester {
public void doTestDenclue() throws IOException, ParseException
{
DelimitedTextParser parser = new DelimitedTextParser();
parser.setResponseIndex(new NominalAttribute("class"), 0);
InputStream in = this.getClass().getResourceAsStream("USCensus1990_data1.csv");
AttributeDataset data = parser.parse("US Census data", in);
double[][] x = data.toArray(new double[data.size()][]);
int[] y = data.toArray(new int[data.size()]);
}
public DenclueTester() {} //constructor
}
The following code is executed in main :
public class Dtest
{
public static void main(String[] args) throws IOException, ParseException
{
DenclueTester dt = new DenclueTester();
dt.doTestDenclue();
}
}
Stack trace:
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at smile.data.parser.DelimitedTextParser.parse(DelimitedTextParser.java:234)
at com.algorithms.DenclueTester.doTestDenclue(DenclueTester.java:18)
at com.algorithms.Dtest.main(Dtest.java:26)
Could anyone help me with that?
Solved issue by placing the csv file into /classes/package_name folder. Thanks
i wrote a simple program which is in my book.
but i'm getting the MalformedURLException exception.This is my code
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args){
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
but my friend said he got it right with the same code.
what's wr9ong with my code? Is it because of the internet connection(I'm using a dial-up connection)
I
Java uses the concept of checked Exceptions. You need to put this code inside a try/catch block, since it is bound to throw a MalformedURLException. Something like
URL imageLocation = null;
try {
imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
Or let the main method throws the Exception like :
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
catch the MalformedURLException using try and catch block
try {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",
JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
Your internet connection would not cause that Exception. (If your URL did not exist, Java would throw an IOException, probably a FileNotFoundException, per URLConnection documentation.) In fact, your code isn't throwing an Exception at all! What you're seeing is a compile error:
$ javac ImageGreet.java
ImageGreet.java:7: error: unreported exception MalformedURLException; must be caught or declared to be thrown
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
^
1 error
When Java tries to turn your program from source code into machine code, it finds a problem, so it stops and asks you to fix it. Your code hasn't run yet -- Java's warning you that there's a problem with your program's source code. (If you're running an IDE, this will show up in a "problems" pane, as opposed to an error message from javac.)
The issue is that you need to catch the MalformedURLException in your code, or declare that main throws MalformedURLException. For example:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation=new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
Note that I've added throws MalformedURLException to the end of your main method, which is the latter of the solutions I suggested above. That tells Java that your main method may propagate an Exception of type MalformedURLException.
Since Java has checked exception you have to add throws MalformedURLException to your methods header or you have to write the method logic inside try/catch blocks.