I am getting a FileNotFoundException while running code.
my filname is filecontent.java...
Definition: I want to create a program having 4 TextFields and 4 TextAreas. If one types the name of the file in TextField, then its content should be shown in corresponding TextArea.
Error :
Exception e : java.io.FileNotFoundException :
My Code :
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class filecontent extends Frame implements ActionListener
{
TextField t[]=new TextField[4];
TextArea ta[]=new TextArea[4];
Button submit,exit=new Button("Exit");
Panel p1;
filecontent()
{
setGUI();
setRegister();
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e : "+ioe);
}
setTitle("FileData");
setVisible(true);
setSize(300,300);
setLocation(500,200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{ System.exit(0); }
});
}
void setGUI()
{
p1=new Panel();
p1.setLayout(new GridLayout(5,4,10,10));
for(int i=0;i<4;i++)
{
t[i]=new TextField(10);
ta[i]=new TextArea();
p1.add(t[i]);
p1.add(ta[i]);
}
submit=new Button("Submit");
p1.add(submit);
p1.add(exit);
}
void setRegister()
{
submit.addActionListener(this);
exit.addActionListener(this);
}
void showfile() throws java.io.IOException
{
FileReader fin[]=new FileReader[4];
FileReader fn=new FileReader("filecontent.java");
BufferedReader br[]=new BufferedReader[4];
for(int i=0;i<4;i++)
{
fin[i]=new FileReader(t[i].getText());
}
int cnt=1;
String s;
fn=fin[0];
br[0]=new BufferedReader(fn);
while(cnt<=4)
{
if((s=br[cnt-1].readLine())!=null)
{
ta[cnt-1].append(s+"");
}
else
{
fin[cnt-1].close();
cnt++;
fn=fin[cnt-1];
br[cnt-1]=new BufferedReader(fn);
ta[cnt-1].setText("");
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e"+ioe);
}
}
else if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static void main(String ar[])
{
new filecontent();
}
}
You don't have a NullPointerException. You have a FileNotFoundException. As the name of this exceptions says this is because a file you try to open isn't found.
The first file access that fails is this one:
FileReader fn=new FileReader("filecontent.java");
If your java file is located within a src (or any other) folder of your project you have to add the folder. E.g. src/filecontent.java
Some other notes:
By convention java class names start with upper case letters
Your variable names t, ta, p1, etc. can be confusing. Why not use textFields, textAreas, panel?
I think you will run into an ArrayIndexOutOfBoundsException in this line while(cnt<=4)
. Array indices start with 0 and end with n - 1 (=3 in your case)
It can help debuging to print out the stacktrace in your catch block: ioe.printStackTrace(). This gives you the exact line number where your code fails
Your exception may have come from this line
FileReader fn=new FileReader("filecontent.java");
I think you should use a full path, not just a file name.
First of all, why don't you use FileDialog instead of textField for the file. Secondly, you are using relative path so for your program to work, the file filecontent.java must be in the same place as your .class file
When reading a file in java the syntax for filepath varies system to system. So you should apply the path according to the operating system you are using.
Also for your code the file filecontent.java should be in the same directory.
Based on your comments, the answer is that the file appears as a.txt in explorer but is actually a.txt.txt Showing file extensions in explorer avoids this issue/confusion.
When you use a file path it is relative to the working directory, i.e. where the application was run. Not where the source code can be found. If you don't know what your working directory is, you should use a full path name.
Related
I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
I've never used java windowbuilder before, however I'm trying to test it with my program which performs operations on sets. It's a Gradle project. I wrote all classes in the default package (I knew that it's discouraged just when I was finished). The program reads a line of operations on sets, parses it and prints the result and keeps doing that while there is a new line input from the user.
I'm trying to make a simple GUI for this program using windowbuilder but I can't figure out how to run the main class in the windowbuilder class and make it take input from a jtextfield and prints output.
My main looks like this:
public static void main(String[] argv) {
new Main().start();
}
private void start() {
hmap = new HashMap<IdentifierInterface, SetInterface<BigInteger>>();
Scanner in = new Scanner(System.in);
// While there is input, read line and parse it.
while (in.hasNextLine()) {
try {
String statement = in.nextLine();
if (statement.trim().isEmpty()) {
System.out.println("error, no statement");
} else {
Scanner statementScanner = new Scanner(statement);
readStatement(statementScanner);
}
} catch (APException e) {
System.out.printf("%s\n", e.getMessage());
}
}
}
I made a new windowbuilder class, with the buttons and text fields, but I got stuck on how to run my main inside the windowbuilder. Your help is appreciated. Thanks in advance.
Eclipse RCP applications are OSGi plug-ins; they do not have a main() method.
Instead your Main class should look like this:
package com.myplugin;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Main implements BundleActivator {
#Override
public void start(BundleContext bundleContext) throws Exception {
// Copy your start logic here
}
}
Then edit META-INF/MANIFEST.MF file and set for example
Bundle-Activator: com.myplugin.Main
This makes your Main class the activator of the plug-in: start() will be invoked at load.
I am trying to run code, but this error shows up. I am using Netbeans on windows, jdk-9, javacv 1.3.2, opencv 3.1.0-1.2. What could be the solution to this?
Part from the main code:
public void start() {
frameGrabber = new FFmpegFrameGrabber("video=Webcam C170");
frameGrabber.setFormat("dshow");
frameGrabber.setImageWidth(1280);
frameGrabber.setImageHeight(720);
logger.debug("Starting frame grabber");
try {
frameGrabber.start(); //line 72
logger.debug("Started frame grabber with image width-height : {}-{}", frameGrabber.getImageWidth(), frameGrabber.getImageHeight());
} catch (FrameGrabber.Exception e) {
logger.error("Error when initializing the frame grabber", e);
throw new RuntimeException("Unable to start the FrameGrabber", e);
}
SwingUtilities.invokeLater(() -> {
window.setVisible(true);
});
process();
logger.debug("Stopped frame grabbing.");
}
Error:
Caused by: org.bytedeco.javacv.FrameGrabber$Exception: avformat_open_input() error -5: Could not open input "video=Webcam C170". (Has setFormat() been called?)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:535)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:465)
at org.imesha.examples.javacv.JavaCVExample.start(JavaCVExample.java:72)
Did you try to pass filename as constructor parameter, but with extension? Based on source file the FFmpegFrameGrabber has 3 constructors and one of option is to pass a String called filename, which mostly means a file name + its extension like "yourfile.mpeg"
When I open the runnable jar file, it still could be opened but it get stuck after half a second like this.
(I cannot post an image, so I post the image here: https://pbs.twimg.com/media/B4RN2_MCYAAi1DD.png)
It works well in eclipse.
When I run it in CMD, it says:
Exception in thread "game" java.lang.NullPointerException: in
at javazoom.jl.decoder.Bitstream.<init>(Unknown Source)
at javazoom.jl.player.Player.<init>(Unknown Source)
at javazoom.jl.player.Player.<init>(Unknown Source)
at lian.xiangru.game.AudioHandler.<init>(AudioHandler.java:12)
at lian.xiangru.game.GameBoard.playSound(GameBoard.java:410)
at lian.xiangru.game.GameBoard.move(GameBoard.java:224)
at lian.xiangru.game.GameBoard.moveTiles(GameBoard.java:271)
at lian.xiangru.game.GameBoard.checkKeys(GameBoard.java:340)
at lian.xiangru.game.GameBoard.update(GameBoard.java:146)
at lian.xiangru.game.Game.update(Game.java:42)
at lian.xiangru.game.Game.run(Game.java:77)
at java.lang.Thread.run(Unknown Source)
It seems something goes wrong with my resources.
This is my playSound method:
private void playSound() {
// how to play mp3 https://www.youtube.com/watch?v=f-7cgX_I220
AudioHandler sound = new AudioHandler(
SOUND_LIST[(int) Math.round((Math.log(highestValue) / Math.log(2))) - 1]);
sound.start();
}
This is my AudioHandler class:
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
class AudioHandler extends Thread {
private Player playMP3;
public AudioHandler(String mp3) {
try {
playMP3 = new Player(getClass().getResourceAsStream(mp3));
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
playMP3.play();
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The lists are:
public static final String[] SOUND_LIST = { "/mayuri.mp3", "/mikoto.mp3",
"/gai.mp3", "/shougo.mp3", "/gintoki.mp3", "/inori.mp3",
"/yuzuru.mp3", "/misaki.mp3", "/armin.mp3", "/alphonse.mp3",
"/alphonse.mp3", "/akane.mp3", "/armin.jpg" };
public static final String[] QUOTE_LIST = { "/mayuri.txt", "/mikoto.txt",
"/gai.txt", "/shougo.txt", "/gintoki.txt", "/inori.txt",
"/yuzuru.txt", "/misaki.txt", "/armin.txt", "/alphonse.txt",
"/alphonse.txt", "/akane.txt", "/armin.txt" };
public static final String[] ICON_LIST = {"/mayuri.jpg", "/mikoto.jpg",
"/gai.jpg", "/shougo.jpg", "/gintoki.jpg", "/inori.jpg",
"/yuzuru.jpg", "/misaki.jpg", "/armin.jpg", "/alphonse.jpg",
"/alphonse.jpg", "/akane.jpg", "/armin.jpg"
};
Thank you !!
NullPointerException when loading a resource usually means that the resource could not be found. This behavior is different than the normal file open, no exception is thrown.
Are your audio files included in your jar? If not, make sure that when you export the Jar, you set the right options so they are included. A better alternative might be to introduce a real build process into your application if you need repeatability.
I just found the reason!
There is a file called Mikoto.mp3 in my resources folder and I typed it as mikoto.mp3 in my code. This could be allowed when I use eclipse to run it. But when I run the runnable jar file, it fails because it is case sensitive.
When I change the file name to mikoto.mp3, it works!
Thanks for your answer!
I try make implementation for comparing the files before they are uploaded.
If file whith name is exist in system ask about create new version or just override it.
Here is the problem, how to get file name?
I can't use receiveUpload(), because after this method file is remove from upload component ?
The problem is that once you start an upload using the Upload component, it can only be interrupted by calling the interruptUpload() method, and you cannot resume anytime later.
The interruption is permanent.
This means you cannot pause in the middle of the upload to see if you already have the file in your system. You have to upload the file all the way.
Considering this drawback, you can sill check in your system if you have the file, after the upload finishes. If you have the file, you can show a confirmation dialog in which you decide wether to keep the file or overwrite.
The following is an example in which I check in the "system" (I just keep a String list with the filenames) if the file has already been uploaded:
public class RestrictingUpload extends Upload implements Upload.SucceededListener, Upload.Receiver {
private List<String> uploadedFilenames;
private ByteArrayOutputStream latestUploadedOutputStream;
public RestrictingUpload() {
setCaption("Upload");
setButtonCaption("Upload file");
addSucceededListener(this);
setReceiver(this);
uploadedFilenames = new ArrayList<String>();
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
latestUploadedOutputStream = new ByteArrayOutputStream();
return latestUploadedOutputStream;
}
#Override
public void uploadSucceeded(SucceededEvent event) {
if (fileExistsInSystem(event.getFilename())) {
confirmOverwrite(event.getFilename());
} else {
uploadedFilenames.add(event.getFilename());
}
}
private void confirmOverwrite(final String filename) {
ConfirmDialog confirmDialog = new ConfirmDialog();
String message = String.format("The file %s already exists in the system. Overwrite?", filename);
confirmDialog.show(getUI(), "Overwrite?", message, "Overwrite", "Cancel", new ConfirmDialog.Listener() {
#Override
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
copyFileToSystem(filename);
}
}
});
}
private void copyFileToSystem(String filename) {
try {
IOUtils.write(latestUploadedOutputStream.toByteArray(), new FileOutputStream(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
private boolean fileExistsInSystem(String filename) {
return uploadedFilenames.contains(filename);
}
}
Note that I have used 2 external libraries:
Apache Commons IO 2.4 (http://mvnrepository.com/artifact/commons-io/commons-io/2.4) for writing to streams
ConfirmDialog from Vaadin Directory (https://vaadin.com/directory#addon/confirmdialog)
You can get the code snippet for this class from Gist: https://gist.github.com/gabrielruiu/9960772 which you can paste into your UI and test it out.