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...");
}
}
Related
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()
I am trying to use ini4j. But I am not able to read the file. The code:
ini = new Wini(new InputStreamReader(new FileInputStream("./setup.ini"), "UTF-8"));
But it is giving me the errors:
Unhandled exception type IOException
Unhandled exception type InvalidFileFormatException
Unhandled exception type UnsupportedEncodingException
Unhandled exception type FileNotFoundException
I already tried "C:\setup.ini" and "setup.ini" and "C:/setup.ini"
I also tried:
ini = new Wini(new InputStreamReader(new FileInputStream(New File("./setup.ini")), "UTF-8"));
The Variable ini is properly declared:
Wini ini;
Any Ideas?
Simple Windows .ini file
[main]
window-color = 00ffff
splash = true
[others]
version = 0.1
developer = Jim
Reading from .ini file
import java.io.File;
import java.io.IOException;
import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;
public class Main {
public static void main(String args[]){
try{
Wini ini;
/* Load the ini file. */
ini = new Wini(new File("config/settings.ini"));
/* Extract the window color value.*/
int windowColor = ini.get("main", "window-color", int.class);
/* Extract the splash screen status. */
boolean splashScreen = ini.get("main", "splash", boolean.class);
/* Show to user the output. */
System.out.println("Your default window color is: " + windowColor);
if(splashScreen){
System.out.println("You have your splash screen activated.");
}else{
System.out.println("You have your splash disabled.");
}
} catch (InvalidFileFormatException e) {
System.out.println("Invalid file format.");
} catch (IOException e) {
System.out.println("Problem reading file.");
}
}
}
Writing to .ini file
import java.io.File;
import java.io.IOException;
import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;
public class Main {
public static void main(String args[]){
Wini ini;
try {
ini = new Wini(new File("config/settings.ini"));
ini.put("main", "window-color", 000000);
ini.put("main", "splash", false);
ini.store();
} catch (InvalidFileFormatException e) {
System.out.println("Invalid file format.");
} catch (IOException e) {
System.out.println("Problem reading file.");
}
}
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);
}
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.
When run it i get this error message in the console. Where have I gone wrong?
"Error displaying C:/Users/Nimit/Desktop/n.txt"
import java.io.IOException;
import javax.swing.*;
public class exmpleText
{
public static void main(String[] args)
{
String url = "C:/Users/Nimit/Desktop/n.txt";
try
{
JFrame frame=new JFrame("Hi");
JEditorPane Pane = new JEditorPane(url);
Pane.setEditable(false);
frame.add(new JScrollPane(Pane));
}
catch(IOException ioe)
{
System.err.println("Error displaying " + url);
}
}
}
Your first mistake is this line.
System.err.println("Error displaying " + url);
The mistake is not in what it is doing, but what it is NOT doing. What is should also be doing is printing out (at least) the exception message, and preferably the stack trace.
And now that you've seen / shown us the stack trace, it is clear what the underlying error is. The string "C:/Users/Nimit/Desktop/n.txt" is not a valid URL. A valid file URL starts with a "file:" scheme.
File URLs with Windows drive letters are written like "file:///C:/Users/Nimit/Desktop/n.txt".
Reference: http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx
Alternatively, you can convert a pathname to a URL using new File("some path").toURL().
You should display the stacktrace in order to know what is really going on, using ioe.printStackTrace()
import java.io.IOException;
import javax.swing.*;
public class ExempleText {
public static void main(String[] args) {
String url = "C:/Users/Nimit/Desktop/n.txt";
try {
JFrame frame=new JFrame("Hi");
JEditorPane Pane = new JEditorPane(url);
Pane.setEditable(false);
frame.add(new JScrollPane(Pane));
} catch(IOException ioe) {
System.err.println("Error displaying " + url);
ioe.printStackTrace();
}
}
}
CORRECTED CODE
import java.io.*;
import javax.swing.*;
import java.net.*;
public class exmpleText
{
public static void main(String[] args)
{
String url = "C:\\Users\\welcome\\z.txt";
File f = new File(url);
try
{
URL x = f.toURL();
System.out.println(x);
JFrame frame=new JFrame("Hi");
JEditorPane Pane = new JEditorPane(x);
Pane.setEditable(false);
frame.add(new JScrollPane(Pane));
frame.setVisible(true);
}
catch(Exception ioe)
{
System.out.println(ioe);
System.err.println("Error displaying " + url);
}
}
}
Add this code after JFrame object creation
try{
editorPane.setContentType("text/html");
Reader fileRead=new FileReader(name); // name is the file you want to read
editorPane.read(fileRead,null);
} catch(Exception e) {
e.printStackTrace();
}