So we got this assignment in a basic java programming course and we're supposed to implement a kind of card deck. To help us with this they have given us resources that will present a GUI on the screen, but when running my program I get a IOException that says that it can't read the input file, most likely since the pathname is wrong. And I dont know how to fix it, we're not even supposed to be in meddling with this code. The error is thrown in this method:
private Image getImg(Card aCard) {
File pathToFile = null;
if (aCard == null) {
pathToFile = new File("cardset-oxymoron/shade.gif");
} else {
String suits = "cdhs";
char c = suits.charAt(aCard.getSuit());
String fileName = String.format("%s/%02d%c.gif", "cardset-oxymoron", aCard.getRank(), c);
pathToFile = new File(fileName);
}
Image img = null;
try {
img = ImageIO.read(pathToFile);
} catch (IOException ex) {
System.err.println("Failed to create image");
ex.printStackTrace();
}
return img;
}
And according to the error stack(?) it is at line 99, which is the
img = ImageIO.read(pathToFile);
line
The folder that the cards are in is inside the project folder, right in between bin and src. using IntelliJ debugger I can see that the the pathToFile is "cardset-oxymoron\02d.gif". The filename is correct as all the cards are "[01-13][c/d/h/s].gif". When I rightclicked and copied the path to the files inside IntelliJ it was using forwardsslashes and not backslashes. But then I checked in explorer and it was the other way around... I have no idea where this is going wrong, any input would be greatly appreciated!
According to your code your files are in directory cardset-oxymoron relative to your JVM run directory. I'm not sure about IntelliJ (I work all the time with Eclipse and Maven), but it could be bin directory.
You can check it by put those 2 lines to see what is it actually (somewhere before your actual code)
File currentDir = new File("./");
System.out.println(currentDir.getAbsolutePath());
Then your cardset-oxymoron must be in that directory. Or you can change file path appropriately.
E.g. if currentDir is bin then pathToFile will be
pathToFile = new File("../cardset-oxymoron/shade.gif");
as well as fileName for other case.
Related
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
So I am trying to copy one file from one place to the other using the solution found here :
Copying files from one directory to another in Java
My code creates the new directory but cant seem to find the file ,even though the landedtitlesFile is pointing to the proper path and file. I always get my "blast" comment in case you were wondering if my program gets to the end of the method.
Thank you for your time and patience.
private File landedtitlesFile = new File("C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Crusader Kings II\\common\\landed_titles\\landed_titles.txt");
private String modPath = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking";
public void createCopyLandedTitles(Boolean vanilla){
if (vanilla == true) {
File dir = new File(modPath + "\\common\\landed_titles");
dir.mkdir();
try{
FileUtils.copyFile(landedtitlesFile,dir);
}
catch (IOException e ){
System.out.println("blast");
}
}
copyFile expects the second parameter to be the destination file, not a destination directory. You need to give it the target name of the file within that directory:
FileUtils.copyFile(
landedtitlesFile,
new File(dir, landedtitlesFile.getName());
Exception objects generally contain some information on the cause. If you print out the exception with e.printStackTrace(); (or rethrow it up the stack with throw new RuntimeException(e);) then you will be able to see what it says.
I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object.
I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
I made a program to read audio files.
At first I did it with absolute path because it's easyer to develop.
Then I cahnge it to relative path because I want to compress it to a *jar.
So I code this method(at first only short later the code:
1.: at first I make a FileArray to save the Files
2.: make the array to save the AudioClip
3.: for loop to read the Clips
Now the code:
private AudioClip[] liesAudioDateien (File inputFile) {
File[] dateFileArray;
AudioClip[] tracks;
dateFileArray = inputFile.listFiles();
tracks = new AudioClip[dateFileArray.length];
for (int i = 0; i < tracks.length; i++) {
if (dateFileArray[i].isFile()) {
try {
tracks[i] = Applet.newAudioClip(dateFileArray[i].toURL());
} catch (IOException ex) {
System.err.println("Error!: -- " + ex.toString());
}
}
}
return tracks;
}
inputFile.listfiles() returns null, as seems my path isn't OK.
But my path is Ok, because I let it print on the command line.
D:\Eclipse\MyProjekt\dist\MyProject.jar\audio.
In NetBeans, it does work. If I make a jar file, it doesn't work.
I have already try:
D:\Eclipse\MyProjekt\dist\MyProject.jar\audio\
/ in place of \
Are you sure this is the correct file path?
D:\Eclipse\MyProjekt\dist\MyProject.jar\audio
The audio directory is in a folder called MyProject.jar?
If your audio files are within the .jar file you cannot use the File class to list them. What you have to do instead is read the entries from the .jar file, like in this question.
I am trying to read a file in Java called "KFormLList.txt". It is saved in the default package along with this program, yet when I try to run it I get this error message: "Error: KFormLList.txt (The system cannot find the file specified)"
What am I doing wrong? Thanks for any help.
import java.io.*;
public class VLOCGenerater {
/**
* #param args
*/
public static void main(String[] args) {
try {
//Read the text file "KFormLList.txt"
FileInputStream fis = new FileInputStream("KFormLList.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String strLine;
int V = 0;
int LOC = 0;
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
System.out.println(strLine);
V++;
}
else {
LOC++;
}
}
System.out.println("V = " + V);
System.out.println("LOC = " + LOC);
dis.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Try putting the text file in the root directory of your project.
The name parameter passed into the FileInputStream constructor is the path name to the file in the file system.
A pathname, whether abstract or in string form, may be either absolute
or relative. An absolute pathname is complete in that no other
information is required in order to locate the file that it denotes. A
relative pathname, in contrast, must be interpreted in terms of
information taken from some other pathname. By default the classes in
the java.io package always resolve relative pathnames against the
current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual
machine was invoked.
I assumed you were using Eclipse, by default Eclipse sets the user.dir to your the root of your project. From reading other material, Netbeans follows the same convention.
This can be tested with the following code, which should output the path to your project:
System.out.println(System.getProperty("user.dir"));
Placing the file in the root of your directory allows it to be found by the FileInputStream.
If you're using NetBeans (perhaps similar for Eclipse), make sure that your file is in NetbeansProjects/YourProject/
If you have compiled your program to .jar file, put the txt to same place where .jar is.
Either you put the file in the "root directory" of your project or provide the "absolute path" of the file as argument to FileInputStream.
Hope that helps. :).
This way, the program expects the file in the working folder,. i.e. where you execute java. For loading from classpath (Default package), try getResourceAsStream.