Throws file not found Exceptions - java

I created a gfx folder inside an android project's assets folder. I stored images which i will be using in my game for android. Since i need to pass the image height and image width converting it to the nearest highest powwer of 2 in andEngine, so i create a ImageUtility class to read image inside the gfx folder and get its height and width.
package org.ujjwal.androidGameUtility;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtilities {
private static final String ABSOLUTE_PATH = "F:\\Games\\TowerOfHanoi\\assets\\gfx\\";
private String fileName = "";
private File imageFile;
private int imageHeight;
private int imageWidth;
public ImageUtilities(String filename){
this.fileName = filename;
this.imageFile = new File(ABSOLUTE_PATH + this.fileName);
try {
processImage();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* this methods set the doucment relative path for the graphics to be used
* and it is mandotry to call before using ImageUtilties object else it will throw filenotFoundException
*
* #param path
*/
private void processImage() throws FileNotFoundException{
if(imageFile.exists()){
try {
BufferedImage image = ImageIO.read(this.imageFile);
this.imageWidth = image.getWidth();
this.imageHeight = image.getHeight();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else{
throw new FileNotFoundException("Either you missed typed filename or haven't called setAssetBasePathMethod setImageBasePath(String path) method");
}
}
public int getImageHeight(){
return this.imageHeight;
}
public int getImageWidth(){
return this.imageWidth;
}
public String getFileName(){
return this.fileName;
}
public File getImageFile(){
return this.imageFile;
}
}
I always get FileNotFoundException with the error msg above. The weird problem is when i access the image file from other java class i don't get any error. I printed the height and width all went exactly i wanted but i could not access the same image file from my android game project. What kind of error is this. I provided absolute filepath for the image. I also tried to compare the file path they were same. Please tell me what error i got, I spend whole day trying to figure out but ...

What #mittmemo mentioned was right, you cannot access the F drive from your phone or emulator. Your computer and android are two different OS. What you can do is instead of putting your file in /assets, you can put it in /raw under resource directory. You can then access it by using:
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}

Related

How to Get Total Page Count From Tiff

I have started to create a new method in our project to return total pages. We are using TIFFTweaker which can be referenced from the following URL - https://github.com/dragon66/icafe/blob/master/src/com/icafe4j/image/tiff/TIFFTweaker.java
In this class I found a method TIFFTweaker.getPageCount() which looks like it wants a RandomAccessInputStream object for their getPageCount().
I've been playing around with trying to get from my file object over to what they're looking for.
What would be the best way to approach this and return the total pages from the tiff?
I have looked over some java docs, stackOverflow and some random blogs but can't seem to figure out how to get from a file object to a randomaccessinputstream.
#Override
public Integer totalPages(File file) {
Integer numberOfPages = 0;
try{
//TIFFTweaker.getPageCount(); - How to pass the file and get the count? Problem is type is a random access input stream and I have a file type
FileInputStream fileInputStream = new FileInputStream(file);
String absolutePath = file.getAbsolutePath();
// return TIFFTweaker.getPageCount();
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
I am expecting a numeric value returned which represents the total number of pages in the TIFF file I'm passing.
Here is what I got to work. #roeygol, thanks for your answer. I had tried to Maven import the dependency but something was broken in that version. Here is what I came up with.
#Override
public Integer totalPages(File file) {
try(
InputStream fis = new FileInputStream(file);
RandomAccessInputStream randomAccessInputStream = new
FileCacheRandomAccessInputStream(fis)
){
return TIFFTweaker.getPageCount(randomAccessInputStream);
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
Try to use this code:
import java.io.File;
import java.io.IOException;
import java.awt.Frame;
import java.awt.image.RenderedImage;
import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class MultiPageRead extends Frame {
ScrollingImagePanel panel;
public MultiPageRead(String filename) throws IOException {
setTitle("Multi page TIFF Reader");
File file = new File(filename);
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
System.out.println("Number of images in this TIFF: " +
dec.getNumPages()); //<< use this function to get the number of pages of your TIFF
// Which of the multiple images in the TIFF file do we want to load
// 0 refers to the first, 1 to the second and so on.
int imageToLoad = 0;
RenderedImage op =
new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
null,
OpImage.OP_IO_BOUND,
null);
// Display the original in a 800x800 scrolling window
panel = new ScrollingImagePanel(op, 800, 800);
add(panel);
}
public static void main(String [] args) {
String filename = args[0];
try {
MultiPageRead window = new MultiPageRead(filename);
window.pack();
window.show();
} catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
Prerequisites for this code is to use jai-codec:
https://mvnrepository.com/artifact/com.sun.media/jai-codec/1.1.3
The main function to be used for is getNumPages()

getResource() inside of .wav sound player class

Simple GUI application for playing sound clips after user selects one with a radio button and pushes the play button. After clean and build, execution from the JAR file results in no sound being played when a clip is selected and the play button is pushed.
Conditions: NetBeans IDE, sounds play successfully in the IDE pathed to the package, path to .wav files in JAR is correct, files are in the executable JAR in the correct directory, uses 2 classes: one for the GUI and a .wav handler class (both work successfully in the IDE. More details in screen shots. I am thinking that there should be a getResource() method call in the Player calss but I don't know how to write it.
The code snippet used to call the resource from within the GUI class. The base is new Player("whateverthefilepathis").start(). (this works fine in the IDE, so no issue there):
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton1.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/fear_converted.wav");
new Player (file.getFile()).start();
}
else if (jRadioButton2.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/initiated_converted.wav");
new Player (file.getFile()).start();
}
This is the Player class used to process the .wav. Within the GUI class, I am using the new Player().start() call. I am thinking that there should be a getResource() call in the Player class but I don't know for sure.
package my.quotesbutton;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Player extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public Player(String wavfile) {
filename = wavfile;
curPosition = Position.NORMAL;
}
public Player(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println("Wave file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
You can't access anything inside a jar file using the java.io.File API, simply because items inside a jar are not files.
You need indeed, as you suspected, to use a getResource() method (or getResourceAsStream()): http://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html
That may look counterintuitive at first, but getResource() works with files as well as jars (or even remote located resources in case of a webapp, as in the linked tutorial), the ClassLoader will deal with the dirty details how the resource is physically accessed. In short: never use the File API for resources - resources should only be accessed using the resource API.

Saving internet icon then re-opening causes EOF with image4j

I'm currently working on a project where I'm attempting to download a .ico file, but for some strange reason, I can't seem to open it programmatically once downloaded. I can however, open the image saved using any image editor or viewer. My code:
public static BufferedImage parseImageLocal(String url) throws IOException {
if (url.endsWith(".ico")) {
return ICODecoder.read(new File(url)).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(new File(url));
} else {
return ImageIO.read(new File(url));
}
}
public static void saveImage(BufferedImage img, String path)
throws IOException {
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
if (!outputfile.exists()) {
outputfile.createNewFile();
}
if (path.endsWith(".ico")) {
ICOEncoder.write(img, outputfile);
} else if (path.endsWith(".bmp")) {
BMPEncoder.write(img, outputfile);
} else {
ImageIO.write(img, "png", outputfile);
}
}
And this is how i download images from the internet:
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
The error is on this line:
return ICODecoder.read(new File(url)).get(0);
It "seems" that you are trying to download the icon from the internet, but you are trying to treat the URL as a File.
Basically, this isn't going to be possible, File won't be able to resolve to an actual physical file.
Instead, you should be using ICODecoder#read(InputStream) and URL#openStream
Something more like...
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
img = ICODecoder.read(is);
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
Updated with example
A web resource is not a File, you can not access it as if they were, instead, you need to use the classes designed for interacting with the internet/network.
For example...
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.sf.image4j.codec.ico.ICODecoder;
public class ReadFavicon {
public static void main(String[] args) {
new ReadFavicon();
}
public ReadFavicon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
BufferedImage img = readIcon(new URL("https://secure.gravatar.com/favicon.ico"));
JOptionPane.showMessageDialog(null, "My FAVICON", "Icon", JOptionPane.PLAIN_MESSAGE, new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public BufferedImage readIcon(URL url) throws IOException {
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
List<BufferedImage> imgs = ICODecoder.read(is);
img = imgs != null ? imgs.size() > 0 ? imgs.get(0) : null : null;
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
}
}
Update with some more ideas
Now. I could be wrong, but when I ran your code, I ran into a serious of problems with the paths...
Let's assume the original url/path is https://secure.gravatar.com/favicon.ico, when you save the image, you do something like...
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
With our original path, this would result in a outputfile of https://secure.gravatar.com/favicon.ico, which is obviously wrong...
We can correct for this by using path.replace("https://", "") as well...
path = path.replace("http://", "");
path = path.replace("https://", "");
File outputfile = new File(path);
File parent = outputfile.getParentFile();
parent.mkdir();
Now, this results in a outputfile of secure.gravatar.com/favicon.ico. I become a little unstuck, as I'm not sure if this is what you want...but it does work for me...
Now, when you read the file, you do something like this...
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
Now, with no evidence to the contray, I have to assume the url has not changed and is still https://secure.gravatar.com/favicon.ico...this means that new File("https://secure.gravatar.com/favicon.ico") will produce an invalid file reference
So, again, I parsed the input...
url = url.replace("https://", "");
url = url.replace("http://", "");
File outputfile = new File(url);
String parentPath = outputfile.getParent();
String name = outputfile.getName();
url = parentPath + File.separator + name;
Which produces secure.gravatar.com\favicon.ico
This all downloaded, wrote and read without error.

jsoup unexpectedly fetching shopwiki image

I am using the following code to fetch images from the web:
import java.io.FileOutputStream;
import java.io.IOException;
import org.jsoup.Jsoup;
public class fetchImageTest {
public static void main(String[] args) throws Exception {
saveImage(args[0], args[1]);
}
private static boolean saveImage(String string, String destination) throws IOException {
string = string.replaceAll(" ", "%20");
try {
byte[] image = Jsoup.connect(string).ignoreContentType(true).timeout(10000).execute().bodyAsBytes();
FileOutputStream os = new FileOutputStream(destination);
os.write(image);
os.close();
return true;
}
catch (IOException e) {
System.out.println("couldn't open " + string);
return false;
}
catch (Exception e) {
System.out.println("couldn't open - general exception" + string);
return false;
}
}
}
Due to a bug in some of my other code, I tried to fetch an image from a broken URL, of the form:
http://shop.foo.comhttp://shop.foo.com/1.jpg
My code ended up fetching a shopwiki image, like
I am using jsoup-1.7.1.jar. Is there a virus on my server? Is there a virus with my jsoup jar file?
I really have no idea ...
Several sites set up a system to protect the recovery of their image.
I guess you try to retrieve images shopwiki.com
I watched their URL to retrieve a picture is it is well established that security.
http://si4.shopwiki.com/i/data/120x120/18/4/2/aHR0cDovL2VjeC5pbWFnZXMtYW1hem9uLmNvbS9pbWFnZXMvSS81MVMwWTBuZHBjTC5qcGc=.jpg

JAR launches fine when run through Terminal, but not when double-clicked

So I'm trying to load a file using a jar. The file is outside of the jar, but in the same folder. When I run the jar form the terminal using java -jar Test.jar it works just fine, but if I run it by double clicking the jar it does not correctly load from the file. I can load external Images just fine with either method, but not a file I have created. This is running on Mac OSX. This problem also seems to exist on Ubuntu. On Windows, however, the File is loaded even more incorrectly.
The Path loaded from seems to be the same for both cases. When running from terminal, the output for numbers is correct. However, when running by double clicking, any number over 127 is loaded improperly. I have researched for hours for a solution, with no avail.
EDIT: This is my manifest
Main-Class: Test
I have created this simple application to demonstrate my problem.
This is what writes the file that will be read.
import java.io.*;
public class TestWriter{
public static void main(String[] args){
try{
// Create the file and FileWriter.
FileWriter out = new FileWriter(new File("test.map"));
// Write some test numbers.
for (int i = 0; i < 481; i += 30)
out.write(i);
// Flush the output (for good measure?)
out.flush();
// Close the output.
out.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
This is what loads the file.
import javax.swing.JComponent;
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class Run extends JComponent{
// Image to be drawn on screen
BufferedImage IMAGE;
// Output to be drawn on screen
String string = "";
// Loading a MAP file - includes loading a bmp image and a .map (txt file).
public Run(){
// MAP name
String map = "test";
System.out.println("Loading map: "+map);
// Get path
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = "";
// Decode path
try{
decodedPath = URLDecoder.decode(path, "UTF-8");
decodedPath = decodedPath.substring(0, decodedPath.lastIndexOf("/") + 1);
} catch (Exception e){
System.out.println("Could not decode path.");
e.printStackTrace();
System.exit(1);
}
// Add decoded path to output string
string += decodedPath;
try{
IMAGE = ImageIO.read(new File(decodedPath+"/"+map+".bmp"));
System.out.println("MAP image loaded.");
} catch (IOException e){
System.out.println("Could not load MAP image.");
e.printStackTrace();
System.exit(1);
}
try{
System.out.println("Loading MAP data.");
// Create a new reader
FileReader in = new FileReader(new File(decodedPath+"/"+map+".map"));
// While there is something left to be read
while (in.ready()){
// add the next input to the output string
string += ", "+in.read();
}
// Close the input (for good measure)
in.close();
System.out.println("Loaded MAP data.");
} catch (Exception e){
System.err.println("Could not load MAP data.");
e.printStackTrace();
System.exit(1);
}
// Repaint the screen to show our newly loaded image and string
repaint();
}
public void paint(Graphics g){
g.drawImage(IMAGE,0,0,null);
g.drawString(string,16,64);
}
}
This is the main method that creates the JFrame and adds the component Run()
import javax.swing.JFrame;
import javax.swing.JComponent;
public class Test{
public static void main(String[] args){
System.out.println("\nInitializing...");
JFrame frame = new JFrame("Test");
int frameWidth = 640;
int frameHeight = 200;
frame.setSize(frameWidth,frameHeight);
frame.setResizable(false);
frame.setLocation(240,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Run());
frame.setVisible(true);
System.out.println("Running...");
}
}

Categories

Resources