Java- can't read input file - java

I am trying to load a png image of a card to an object but I keep getting the following error:
"C:\Program Files\Java\jdk-9\bin\java" "-javaagent:C:\Users\trevo\Documents\JetBrains\IntelliJ IDEA Community Edition 2017.2.5\lib\idea_rt.jar=60524:C:\Users\trevo\Documents\JetBrains\IntelliJ IDEA Community Edition 2017.2.5\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\trevo\Desktop\Deck\out\production\Deck com.company.Card_Class
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at com.company.Card_Class.main(Card_Class.java:21)
Process finished with exit code 1
Here is my code:
package com.company;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Card_Class {
private String suit, face;
private int value;
private BufferedImage cardimage;
public Card_Class(String suit, String face, int value, BufferedImage cardimage) {
this.suit = suit;
this.face = face;
this.value = value;
this.cardimage = cardimage;
}
public static void main(String[] args) throws IOException {
Card_Class KingOfAxes = new Card_Class("Diamonds", "King", 13, ImageIO.read(new File("KingOfAxes.png")));
System.out.println("King");
}
}
I have all my png card files in a folder labeled deck which is the project name.

Try to write the full file path to the console to see if your file path is correct.
Maybe print the absolute path of your file to stdout to see if your path is correct. You should also check if your image exists and is readible before you use it. Here is an example for both:
public static void main(String[] args) throws IOException {
System.out.println(new File("KingOfAxes.png").getAbsolutePath()); // Try this to pinpoint your issue
File king = new File("KingOfAxes.png");
if(king.canRead()){ // Check if your file exists and is readable before you use it
JavaAssignmentPanel KingOfAxes = new JavaAssignmentPanel("Diamonds", "King", 13, ImageIO.read(new File("KingOfAxes.png")));
} else{
throw new IOException(king.getName() + " is not readable!"); // Not readable -> Throw exception
}
System.out.println("King");
}

Related

Moving large files in java

I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.

File Not Found Exception - Can't see the issue

I've tried directly linking using the entire path but that hasn't solved it either.
package eliza;
import java.io.*;
public class Eliza {
public static void main(String[] args) throws IOException {
String inputDatabase = "src/eliza/inputDataBase.txt";
String outputDatabase = "src/eliza/outputDataBase.txt";
Reader database = new Reader();
String[][] inputDB = database.Reader(inputDatabase);
String[][] outputDB = database.Reader(outputDatabase);
}
}
Here is the reader class:
package eliza;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
public String[][] Reader(String name) throws IOException {
int length = 0;
String sizeLine;
FileReader sizeReader = new FileReader(name);
BufferedReader sizeBuffer = new BufferedReader(sizeReader);
while((sizeLine = sizeBuffer.readLine()) != null) {
length++;
}
String[][] database = new String[length][1];
return (database);
}
}
Here's a photo of my directory. I even put these text files in the "eliza" root folder: here
Any ideas?
Since you are using an IDE, you need to give the complete canonical path. It should be
String inputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\inputDataBase.txt";
String outputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\outputDataBase.txt";
The IDE is probably executing the bytecode from its bin folder and cannot find the relative reference.
give the exact path like
String inputDatabase = "c:/java/src/eliza/inputDataBase.txt";
you have not given the correct path, Please re check
try
{BASE_PATH}+ "Eliza/src/inputDataBase.txt"
The source directory tree isn't generally present during execution, so files that are required at runtime shouldn't be put there ... unless you're going to use them as resources, in which case their pathname is relative to the package root, and does not begin with 'src', and the data is accessed by a getResourceXXX() method, not via a FileInputStream.

How to play an mp3 file in java

I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}

How to get the single images of an mp4-Movie in Java

I want to do some image analysis on a video that's stored in .mp4 format. Therefore I need a way to just get the images of this movie in Java.
I goolged a lot and found some libraries like jcodec and jaad. BUT I wasn't able to get the things running with these libraries. And as I found out, there were examples (at least I found none) that showed my usecase.
Can you help me? Do you know any library that can do what I need and is running at least on Win7 64 bit.
Or do you know how to accomplish this with jcodec?
edit:
As I wrote, I tried it with jcodec. I found out how to get the data of a frame, but not how I can get it into something like a BufferedImage or so. I expect that these data isn't in a simple RGB format but in any compressed format or so. (Am I right with that?) I don't know to to decode this data.
You can get the data of a frame with jcodec as follows (at least as far as I understand this):
public static void main(String[] args) throws IOException, MP4DemuxerException {
String path = "videos/video-2011-09-21-20-07-21.mp4";
MP4Demuxer demuxer1 = new MP4Demuxer(new FileInput(new File(path)));
DemuxerTrack videoTrack = demuxer1.getVideoTrack();
Packet firstFrame = videoTrack.getFrames(1);
byte[] data = firstFrame.getData();
}
I also found the following:
http://code.google.com/p/jcodec/source/browse/trunk/src/test/java/org/jcodec/containers/mp4/DitherTest.java?r=70
But this isn't working (has compile errors) with the downloadable jar-package.
you could use jcodec(https://github.com/jcodec/jcodec) in the followinf program i am extracting frames from a video.
/*
* To extract frames from a mp4(avc) video
*
*/
package avc_frame;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jcodec.api.FrameGrab;
import org.jcodec.api.JCodecException;
public class Avc_frame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, JCodecException {
long time = System.currentTimeMillis();
for (int i = 50; i < 57; i++) {
BufferedImage frame = FrameGrab.getFrame(new File("/Users/jovi/Movies/test.mp4"), i);
ImageIO.write(frame, "bmp", new File("/Users/jovi/Desktop/frames/frame_"+i+".bmp"));
}
System.out.println("Time Used:" + (System.currentTimeMillis() - time)+" Milliseconds");
}
}
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber.Exception;
public class Read{
public static void main(String []args) throws IOException, Exception
{
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("C:/Users/Digilog/Downloads/Test.mp4");
frameGrabber.start();
IplImage i;
try {
i = frameGrabber.grab();
BufferedImage bi = i.getBufferedImage();
ImageIO.write(bi,"png", new File("D:/Img.png"));
frameGrabber.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Error: Could not find or load main class openWordDocument

I am trying to open Microsoft Word document using jacob.
Below is code:
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class openWordDocument {
private static final Integer wdNewBlankDocument = new Integer(0);
private static final Variant vTrue = new Variant(true);
private static final Variant vFalse = new Variant(false);
private static ActiveXComponent activeXWord = null;
private static Object activeXWordObject = null;
public static void main(String[] args) {
try {
activeXWord = new ActiveXComponent("Word.Application");
activeXWordObject = activeXWord.getObject();
Dispatch.put(activeXWordObject, "Visible", vTrue);
//activeXWordObject = null;
}
catch (Exception e) {
quit();
}
}
public static void quit() {
if (activeXWord != null) {
System.out.println("quit word");
//calls the Quit method of MS Word, this will close MS Word
activeXWord.invoke("Quit", new Variant[] {});
ComThread.Release();
activeXWord.release();
System.out.println("quit word");
}
}
}
When I am running above code getting error Error: Could not find or load main class openWordDocument
It's my mistake, I added .dll file in the classpath so I am unable to compile the java file. I removed that dll file after that, jvm started compiling and able to fine the class file.
Warning !!!
Check your external libraries (such as .jar files) path were added to to your project.
The path should have regular format. For example it supposed to not have special characters like as "+", ... or space.
I had that serious problem before in Eclipse IDE, change the path directory of my project library and then everything is okay again.

Categories