I am having difficulties saving pictures that I have loaded. The picture is saved under the same folder where this program is. An error keeps reappearing. The error screen is below
Error
---------- Capture Output ----------
>"C:\Program Files\Java\jdk1.6.0_22\bin\java.exe" loadapicture
java.lang.NoClassDefFoundError: loadapicture
Caused by: java.lang.ClassNotFoundException: loadapicture
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: loadapicture. Program will exit.
Exception in thread "main"
> Terminated with exit code 1.
My program
import hsa.*;
import java.awt.*;
// Look at all of these extra imports needed for a picture file
import java.io.File;
import java.io.IOException;
import java.awt.image.*;
import javax.imageio.*;
public class loadapicture{
public static void main(String[] args){
Console con = new Console();
// Variables need to open a picture file
File tictactoefile;
BufferedImage tictactoeimage;
tictactoefile = null;
tictactoeimage = null;
// Now that the variables are created.. Time to load the picture into the variables
// BTW You need to load the file using a block called try/catch
// Becuase if the file does not exist, you need to catch the error
// You can use jpg, gif, and bmp
try{
// Trying to open the file and loading it
tictactoefile = new File("");
tictactoeimage = ImageIO.read( owin.jpeg);
}catch(IOException e){
// If the file is not found, this will happen
con.println("ERROR... IMAGE FILE NOT FOUND");
}
con.drawImage(tictactoeimage, 100, 100, null);
// Yes you can do all of this in a method
}
}
How to download & save image correctly?
I guess you just need to specify path to your class
"C:\Program Files\Java\jdk1.6.0_22\bin\java.exe" -classpath <path to your class> loadapicture
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 am trying to get a CSV from the report using this well-known plugin and the example from its documentation, but it throws an exception. I wonder why, because I just copied most of the code from the doc.
My code is:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.emitter.csv.CSVRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
public class RunReport {
static void runReport() throws FileNotFoundException, BirtException {
String resourcePath = "C:\\Users\\hpsa\\workspace\\My Reports\\";
FileInputStream fs = new FileInputStream(resourcePath + "new_report_1.rptdesign");
IReportEngine engine = null;
EngineConfig config = new EngineConfig();
config.setEngineHome("C:\\birtre\\birt-runtime-4_3_2\\");
config.setLogConfig("C:\\birtre\\", Level.FINE);
config.setResourcePath(resourcePath);
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
engine.changeLogLevel(Level.FINE);
IReportRunnable design = engine.openReportDesign(fs);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
CSVRenderOption csvOption = new CSVRenderOption();
String format = CSVRenderOption.OUTPUT_FORMAT_CSV;
csvOption.setOutputFormat(format);
csvOption.setOutputFileName("newBIRTcsv.csv");
csvOption.setShowDatatypeInSecondRow(true);
csvOption.setExportTableByName("SecondTable");
csvOption.setDelimiter("\t");
csvOption.setReplaceDelimiterInsideTextWith("-");
task.setRenderOption(csvOption);
task.setEmitterID("org.eclipse.birt.report.engine.emitter.csv");
task.run();
task.close();
Platform.shutdown();
System.out.println("Report Generated Sucessfully!!");
}
public static void main(String[] args) {
try {
runReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am getting the exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/CoreException
at org.eclipse.birt.core.framework.Platform.createPlatformLauncher(Platform.java:115)
at org.eclipse.birt.core.framework.Platform.startup(Platform.java:74)
at com.demshin.birttest.RunReport.runReport(RunReport.java:26)
at com.demshin.birttest.RunReport.main(RunReport.java:55)
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.CoreException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 4 more
I found the package org.eclipse.core.runtime and registered in the build path, but then I am getting the same exception. Indeed, there are no any CoreException.class in the org.eclipse.core.runtime package. What am I doing wrong?
Setting the engine home is deprecated and most of the time it will prevent the Platform to start, such in your case. Remove this line:
config.setEngineHome("C:\\birtre\\birt-runtime-4_3_2\\");
You just have to ensure the birt runtime 4.3.2 is in the classpath of your context. Furthermore i would recommend you try to generate a native format such pdf first, and then try with a csv format.
I was trying a lot of variants of importing different jars, but finally i found the weird decision here:
go to the Project Explorer, right-mouse click on properties for the
project, go to Java Build path, Click on the External Jars button,
then select all the libraries under
C:\birt_runtime\birt-runtime-2_1_0\ReportEngine\lib\ folder
This made chaos there, but at least it starts.
I've got a problem with my classpath within a jar file. With pictures
getClass().getResource("picture.png") works fine. But I need to get a mp3 file.
If I put in the whole path outside of the jar file it works just fine, however if i try it without the full path like getClass().getResource("picture.png") it says "File not Found".
So I'm looking for a solution for the path of song.mp3 so that if I build the .jar and open it on a different computer the song still plays.
this is my code:
package bgmusic;
import java.io.*;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class Bgmusic {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try{
Player player = Manager.createPlayer(new MediaLocator(new File("song.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
If the file is inside of your jar, you can not use new File("song.mp3");. The file expects it to be inside of your normal os path, which it's not.
To get files from within your jar you need to use getResource
Example, assuming song.mp3 is in the root of your jar file and not in a directory:
URL url = this.getClass().getResource("song.mp3");
From within a static method you should be able to get it as follows
URL url = BgMusic.class.getResource("song.mp3");
I have a web app that needs to be able open a file locally on a client machine, with the ability to save the file after editing. The web app generates a document on the server in a folder that is shared out via WebDAV & FTP and this folder is mounted on the client machine.
I cannot use a file:// type URI as it would not permit saving back to the server.
I intend trying to solve the problem with a small java applet embedded in the web app that handles this file opening, but I am having difficulties with permissions in Java. (Java isn't my field of expertise). Anyhow, I've narrowed the code down to the following:
localfile.html
<html>
<body>
<input id="input" value="Call from Javascript" type="button" onclick="callApplet('/Users/conor/1.txt')">
<script type='text/javascript'>
function callApplet(path) {
applet = document.getElementById('localfile');
applet.openFile(path);
}
</script>
<applet id="localfile" code="localfile.class" archive="localfile.jar" width="150" height="50"></applet>
</body>
</html>
localfile.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I have compiled, created a jar file and signed it from the java source.
This produces a page with two buttons - a Java one (for testing) and a Javascript one. The Java button works fine as expected - and I can save the file etc. I want to pass the file path to the applet though so it is really the Javascript button I wish to get working. The Javascript one throws the following though:
Stack Trace
java.security.AccessControlException: access denied ("java.awt.AWTPermission" "showWindowWithoutWarningBanner")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:366)
at java.security.AccessController.checkPermission(AccessController.java:560)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.awt.Desktop.checkAWTPermission(Desktop.java:239)
at java.awt.Desktop.open(Desktop.java:267)
at localfile.openFile(localfile.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
I have also tried embedding the desktop.open call into a doPrivileged block, as follows:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
but that throws error for javascript & java buttons as follows:
java.lang.SecurityException: class "localfile$1" does not match trust level of other classes in the same package
Any help would be appreciated.
Got it to work, so thought I'd post the solution here...
When I was compiling the java file with the doPrivileged call in it, the javac compiler creates two files - localfile.class and localfile$1.class. I wasn't sure initially what the localfile$1.class was and just presumed it was a temporary file of some sort. It was however a class file corresponding to the anonymous class within the doPrilileged block and needed to be included in the .jar file and properly signed.
So anyway, html file is as before, and final java file is as follows:
localfile.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
private static final long serialVersionUID = 1L;
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I also found that there was no need to have the javascript in the html file create the applet and insert it into the DOM. I think this was mentioned in the link #VGR linked to but it worked for me without it.
Thanks for all the help guys!
I wanna make a program automatically tagger the text in a directory. Here's my first step.
I made a little change to TaggerDemo.java. But it is not working properly as expected.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
class auto{
public static void main (String[] args) throws Exception{
MaxentTagger tagger = new MaxentTagger("models/left3words-wsj-0-18.tagger");
#SuppressWarnings("unchecked")
List<List<HasWord>> sentences = tagger.tokenizeText(new BufferedReader(new FileReader(args[0])));
for (List<HasWord> sentence : sentences) {
ArrayList<TaggedWord> tSentence = tagger.tagSentence(sentence);
System.out.println(Sentence.listToString(tSentence, false));
}
}
}
This is the error i got.
Loading default properties from trained tagger models/left3words-wsj-0-18.tagger
Reading POS tagger model from models/left3words-wsj-0-18.tagger ... done [2.9 sec].
Exception in thread "main" java.io.FileNotFoundException: sample-input.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at java.io.FileReader.<init>(FileReader.java:41)
at auto.main(auto.java:17)
Why it says file not found?
When i tried to compile it under terminal, it says edu.stanford.nlp.ling.* can not be imported...
Thanks a lot.
It seems that you don't have the file sample-input.txt in the current directory.
To see your current directory, use:
File f = new File(".");
System.out.println(f.getAbsolutePath());