I'm writing code for a music player in Java FX, I use the MediaPlayer class, which is initialized by a Media class. So far I think that the sources for the Media constructors must be URI in Strings, so I've writen this code for adding a list of song files to a playlist and so playing such list:
public void setPlaylist (List<File> lista) {
songsList.clear();
for (File s : lista) {
songsList.add(s.toURI());
}
}
This works fine. However, when I want to get a File containing the path of a folder, and inputing each file's name in URI format I get some trouble, this is what I've tried so far:
public void setPlaylist (File folder) {
songsList.clear();
for (String s : folder.list()) {
try {
songsList.add(new URI("file:///" + (folder + "\\" + s).replace("\\", "/").replaceAll(" ", "%20")));
} catch (URISyntaxException ex) {
Logger.getLogger(PlayList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I'm getting error logs like this:
SEVERE: null java.net.URISyntaxException: Illegal character in path at
index 78:
file:///C:/Users/Diego%20Aguilar/Music/3%20Grandes%20de%20la%20Banda/AlbumArt_{9AEABE24-F5A2-441C-A71A-D061E000A9BA}_Large.jpg
Use File#toURI() as you were using before to avoid running into encoding issues and make use of a FilenameFilter to restrict the list to media files only. Here's how the code would look then.
public void setPlaylist (File folder) {
songsList.clear();
File[] musicFiles = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".m4a"));
}
});
for (File file : musicFiles) {
songsList.add(file.toURI());
}
}
See JavaDocs: FilenameFilter, File#toURI()
Instead of using String s : folder.list() use File s : folder.listFiles() ... then use the URL from the files.
Your file URI contains an angular bracket {, which is causing SEVERE: null java.net.URISyntaxException
You need to have a valid file path to create a proper URI.
Here is the link to URI RFC for referring what is allowed and what is not allowed in a URL.
Related
I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json.
Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:
public class CommonTestUtility {
public static String getFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
}
Now while calling this function as
class ServerTest {
#Test
void test_loadResource() {
String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}
}
, It's giving me the error as:
CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.
I tried to include the src/test/resources/ in the run configuration
of Junit ServerTest.java, but still it's not able to find out the
resource
How to resolve this issue?
https://mkyong.com/java/java-read-a-file-from-resources-folder/
This above link might be helpful.
The getResource() method return an URI you need to change
.getFile() function to. toURI().
Simple code
private File getFileFromResource(String fileName) throws URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
I recreated the same scenario you describe and your code works for me.
Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.
I am creating a java app that will extract the embedded thumbnail inside of a Powerpoint (PPTX) document. Since pptx files are zip archives, I am trying to use TrueZip to get the thumbnail found inside of the archive. Unfortunately whenever I try running my application it throws an IOException stating that the file is missing C:\Users\test-user\Desktop\DocumentsTest\Hello.pptx\docProps\thumbnail.jpeg (missing file)
Below is the code I use to get the thumbnail:
public Boolean GetThumbPPTX(String inFile, String outFile)
{
try
{
TFile srcFile = new TFile(inFile, "docProps\\thumbnail.jpeg");
TFile dstFile = new TFile(outFile);
if(dstFile.exists())
dstFile.delete();
srcFile.toNonArchiveFile().cp_rp(dstFile);
return dstFile.exists();
} catch (IOException ex) {
Logger.getLogger(DocumentThumbGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
Where inFile is the absolute path of the pptx file and outFile is the path that the thumbnail will be copied to. I can verify that the archive does have a thumbnail inside of it at the same exact path.
Can someone help please?
I just found the answer. It seems I did not have the Zip driver configured correctly. I added this to my class constructor and it all works now:
TConfig.get().setArchiveDetector(new TArchiveDetector(
TArchiveDetector.NULL,
new Object[][] {
{ "zip|pptx", new ZipDriver(IOPoolLocator.SINGLETON)},
}));
I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
you can use filenamefilter class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter instance an override accept method how you want
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
You need to read the directory and iterate inside it.
it is more a question on Java access to file systems than about MVC
I wrote the following function that will search for all the text files inside a directory.
public static void parseDir(File dirPath)
{
File files[] = null;
if(dirPath.isDirectory())
{
files = dirPath.listFiles();
for(File dirFiles:files)
{
if(dirFiles.isDirectory())
{
parseDir(dirFiles);
}
else
{
if(dirFiles.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
}
else
{
if(dirPath.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
see if this helps.
provide a text box to user to enter the path of directory.
File userDir=new File("userEnteredDir");
File[] allfiles=useDir.listFiles();
Iterate allFiles to filter .txt files using getExtension() method
I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
you can use filenamefilter class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter instance an override accept method how you want
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
You need to read the directory and iterate inside it.
it is more a question on Java access to file systems than about MVC
I wrote the following function that will search for all the text files inside a directory.
public static void parseDir(File dirPath)
{
File files[] = null;
if(dirPath.isDirectory())
{
files = dirPath.listFiles();
for(File dirFiles:files)
{
if(dirFiles.isDirectory())
{
parseDir(dirFiles);
}
else
{
if(dirFiles.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
}
else
{
if(dirPath.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
see if this helps.
provide a text box to user to enter the path of directory.
File userDir=new File("userEnteredDir");
File[] allfiles=useDir.listFiles();
Iterate allFiles to filter .txt files using getExtension() method
We use a lot of legacy package.html files in our project and we want to convert them to package-info.java files. Doing that manually isn't an option (way too many files). Is there a good way to automate that?
We want to convert them for a couple of reasons:
From the javadoc specs: This file is new in JDK 5.0, and is preferred over package.html.
To not mix both types of files in the same codebase
To avoid that Intellij/Eclipse builds put those *.html files in our classes dirs (and possibly in a release binary jars) so they behave like our other normal html resources.
You may need to change the directory separator if you're not running windows. Also, the conversion is a bit of a hack, but it should work. Out of curiosity, how many packages do you have that manual isn't an option?
public class Converter {
public static void main(String[] args) {
File rootDir = new File(".");
renamePackageToPackageInfo(rootDir);
}
private static void renamePackageToPackageInfo(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return "package.html".equals(name);
}
});
for (File file : files) {
convertFile(file);
}
// now recursively rename all the child directories.
File[] dirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File subdir : dirs) {
renamePackageToPackageInfo(subdir);
}
}
private static void convertFile(File html) {
// determine the FQN package name
String fqpn = getPackageName(html);
// check if package-info.java already exists
File packageInfo = new File(html.getParent(), "package-info.java");
if (packageInfo.exists()) {
System.out.println("package-info.java already exists for package: "+fqpn);
return;
}
// create the i/o streams, and start pumping the data
try {
PrintWriter out = new PrintWriter(packageInfo);
BufferedReader in = new BufferedReader(new FileReader(html));
out.println("/**");
// skip over the headers
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("<BODY>"))
break;
}
// now pump the file into the package-info.java file
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("</BODY>"))
break;
out.println(" * " + line);
}
out.println("*/");
out.println("package "+fqpn+";");
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// queue the package.html file for deletion
//html.deleteOnExit();
}
private static String getPackageName(File file) {
StringBuilder path = new StringBuilder(file.getParent());
// trim the first two characters (./ or .\)
path.delete(0, 2);
// then convert all separators into . (HACK: should use directory separator property)
return path.toString().replaceAll("\\\\", ".");
}
}
The IntelliJ guys have made an intention to do this for all files. It's been resolved and will probably be released in the next IntelliJ release.
To do this in batch mode in IDEA:
In settings, activate the inspection gadget "'package.html' may be converted to 'package-info.java' inspection"
Open a package.html file
You see a banner fix the inspection on top the file
Click on the settings icon at the right on the banner
Select "Run inspection on" >> "Whole project"
Click on "Convert to package-info.java" >> OK
Optionally remove the inappropriate lines (sed -i "/Put #see and #since/d" `find . -name "package-info.java"`)