IntelliJ Idea - Cannot find input file(bank.in) when running through IntelliJ - java

I have a homework and I did it on Linux, Visual Studio Code, and the command line. It was working perfectly fine until I need to debug my code. So I migrated to Windows 10 because I had IntelliJ IDEA installed there. I compiled the code and place the input file "bank.in" in the same folder as the compiled "MyClass.class"
However, when I run the program from IntelliJ, my code catches the exception that it cannot find the file "bank.in" when it is just in the same folder as "MyClass.class".
My method in creating the bank.in was, right clicking the out folder from IntelliJ and adding a new file and adding the bank.in contents from there
I've tried running it through cmd.exe using java MyClass and it works perfectly. No exceptions are caught.
But when run through IntelliJ IDEA, it shows
Cannot find bank.in...
Exiting the program...
This is the part of my code where I input my file.
public void main(String[] args)
{
String fileName = "bank.in";
FileReader bank = null;
BufferedReader bankBuffered = null;
try
{
bank = new FileReader(fileName);
bankBuffered = new BufferedReader(bank);
}
catch(FileNotFoundException f)
{
System.out.printf("%s is not found.%n%n", fileName);
System.out.printf("Exiting the program...%n");
System.exit(0);
}
}
This is my project folder structure
MyProject
-.idea
-encodings.xml
-misc.xml
-modules.xml
-workspace.xml
-out
-MyClass.class
-bank.in
-src
-MyClass.java
When I run it through cmd.exe, it works fine. Is there any workaround through this? Thank you.

Related

Jar file not working (filenotfoundexception when running in cmd)

I know this topic has been up a lot of times and I have been looking at stackoverflow for hours after the sollution but still not working. From Eclipse I can't make my jar-file work when exporting a runnable jar-file. The program is working perfectly in Eclipse when I run it but when I try to open the jar-file the screen is going black for a second then nothing happens. I try to open it in command with java -jar nameoffile.jar and there is filenotfoundexception. This is what it looks like in cmd when I have tried to run it.
Do anyone have any suggestions?
Thanks
The problem is how you get your resources.
You put your wav file in src folder an the try get them using FileInputStream, that's not going to work.
If you put your file into the jar you should access them throug:
getClass().getResourceAsStream(filepath)
Something like this.
public class LoadFile {
public static void main(String[] args) throws Exception {
InputStream stream =
LoadFile.class.getResourceAsStream("/songwavs/s1_..._.wav");
AudioSystem.getAudioFileFormat(stream);
AudioSystem.getAudioFileFormat(url);
}
}
That's just an example, the point is that being the resource inside the jar, the ClassLoaders are the tool to get it.
So, inside a non static method you could use:
public void myMethod() throws Exception{
InputStream stream = getClass().getResourceAsStream("/songwavs/s1_..._.wav");
AudioSystem.getAudioFileFormat(stream);
}
In some circumstance the you need to use the Thread classloader like this:
public void myMethod2() throws Exception{
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/songwavs/s1_..._.wav");
AudioSystem.getAudioFileFormat(stream);
}
Then you can put read your file both when running from eclipse or from the jar.
Much more could be said about how to package an application and deploy it, but that's just a start.

NoClassDefFoundError when attempting to compile main class in Java program, while all resources are imported

I'm creating a small app to send messages to phone numbers using google voice. I made a simple test case that works in Eclipse and can send out messages as expected. However, when I try to run it on a terminal, I keep running into issues. Here is the main class I've written:
import java.io.IOException;
import com.techventus.server.voice.Voice;
public class main_WUB {
public static void main(String[] args) {
// TODO Auto-generated method stub
String username = "wake.up.bot.acc";
String password = "wakeupbotacc";
String originNumber = #;
String pavlePhone = #;
String wakeupMessage = "txt from main_WUB";
try {
Voice voice = new Voice(username, password);
voice.sendSMS(pavlePhone, wakeupMessage);
System.out.println("IT WORKED?");
//voice.call(originNumber, pavlePhone, "1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I've transferred the class into a remote server to test on a linux machine, however, these are the issues I've come up against. When I try to run the main class using
java main_WUB
it returns an exception, stating
Exception in thread "main" java.lang.NoClassDefFoundError: com/techventus/server/voice/Voice at main_WUB.main<main_WUB.java:18> ...
What confuses me is that I ran into this error beforehand in eclipse, and fixed it by importing the reference library in which com.techventus.server.voice.Voice is contained. Now I'm running into the same issue when trying to compile directly. Is there a way to fix this? What am I missing in my command? Any help would be appreciated.
create a jar file for your entire project in eclipse. Procedure for making jar file in eclipse -> right click on your project -> export -> java -> runnable jar file -> select main_WUB in launch configuration drop down list box -> select radio button "extract required libraries into generated jar" -> finish.
now open cmd promt -> goto the path where jar is there -> then give the command "java -jar main_WUB"
It should work.
You need build the JAR with all Libs (dependences) includes.
When you build your project in Eclipse, use the option 'Build with dependences'

How to open your eclipse project in a window?

How do I export my Eclipse project so that it is its own console application sort of thing.
Every time I try to run the .jar file after exporting it, a window pops up saying that it couldn't open the program. Is there some code I need to enter in order to make it its own window, like when you run it in eclipse, except it is its own window and application. Here is an example of how I have coded it:
public class main {
public static void main(String[] args) {
Scanner text = new Scanner(System. in );
System.out.println("Ready:");
boolean loop2 = true;
while (loop2 = true) {
String text1 = text.nextLine();
switch (text1) {
case "hi":
System.out.println("Greetings!");
break;
}
}
}
}
Any help would be nice! I am trying to make this for sending to my friends, too, just so you know.
In the navigator view, right-click on your project > Export > Java > Jar. Be sure to indicate your class as main class.
Then, once saved, you can run the jar by double clicking on it, or using java -jar jarfile.jar from command line.

.jar file won't run? (I feel like I'm missing something obvious, looked to solutions myself before coming here.)

I wanted to find out how to create an executable .jar file, so I wrote a small sample program to test it. This sample program takes some default text and turns it into some code based on the Caesar code. Anyway, it outputs normally when run in Eclipse.
I doubt this helps, but here's the source code for the two java classes.
Main.java
public class Main {
public static void main (String [] args){
Caesar caesarCode = new Caesar();
caesarCode.setDecodedText("this");
caesarCode.setShiftPos(3);
String cipherText = caesarCode.deencode(caesarCode.getDecodedText(), caesarCode.getShiftPos());
System.out.print(cipherText+"\n");
String plainText = caesarCode.deencode(cipherText, caesarCode.getShiftPos()*-1);
System.out.print(plainText);
}
}
Caesar.java
public class Caesar {
// global variables
String encodedText; // encoded text
String decodedText; // decoded text
int shiftPos; // shift positions to decode message
// getters and setters
public String getEncodedText() {
return encodedText;
}
public void setEncodedText(String encodedText) {
this.encodedText = encodedText;
}
public String getDecodedText() {
return decodedText;
}
public void setDecodedText(String decodedText) {
this.decodedText = decodedText;
}
public int getShiftPos() {
return shiftPos;
}
public void setShiftPos(int shiftPos) {
this.shiftPos = shiftPos;
}
public String deencode (String plainTextArg, int shiftPosArg) {
// variables
String plainText = plainTextArg;
char[] cipherTextArray;
String cipherText;
int plainTextSize;
int shiftPos = shiftPosArg;
// initialize variables
char[] plainTextArray = plainText.toCharArray();
plainTextSize = plainTextArray.length;
cipherTextArray = new char[plainTextSize];
// shift cipher String by shiftPos
for (int i = 0; i < plainTextSize; i++){
cipherTextArray[i] = (char) (plainTextArray[i] + shiftPos);
}
cipherText = String.valueOf(cipherTextArray);
// return cipher text
return cipherText;
}
}
I created my .jar file this way (on a Mac):
Created two directories on Desktop: "classes" and "source"
Copied my two files (Caesar.java, Main.java) into the source folder.
I compiled the files into .class files in the classes directory with the command "javac -d ../classes *.java"
I created a manifest.txt file with the line "Main-Class: Main", and saved it as "manifest.txt" in the classes directory.
I then created the .jar file with this command "jar -cvmf manifest.txt main.jar *.class".
The main.jar file was created successfully.
The problem is, when I ran it, nothing happened - no warnings, no popups, no error messages.
I'm thinking that it has something to do with the fact that it outputs to the terminal, but I can't wrap my head around it. I've also looked at many threads on this forum and others, but can't seem to see the problem. I'm going to experiment to see if it works for a GUI application in the meanwhile.
Greatly appreciate your help on this, thanks!
I'm thinking that it has something to do with the fact that it outputs to the terminal
If you want to see console output from your program then you will have to run it in the Terminal with java -jar main.jar. If you double click the JAR in the Finder or use the open command then it will run but any output will go to the system console log rather than being displayed directly. You can show system console messages by running syslog -C.
In Windows, press Windows+R to invoke "Run..." dialog. Type cmd there and hit Enter. The Command Prompt window will appear (it's black).
At the prompt type cd %USERPROFILE%\Desktop\classes and hit Enter.
Then type command as suggested above: java -jar main.jar
It is possible to create executable jars from within eclipse if you want to.
Right click on your project -> Export -> Java -> Runnable JAR file.
Note that You might need to run your jar file from the command line using java -jar <jarFile> to see System.out.println() and error messages.

Working with file in Eclipse

I have instruction to run program in command line, for example:
java SetTest < alice30.txt
I wonder how to do this in Eclipse. I tried to put this in Run Configuration like this:
Another thing I don't know is where to put this file (alice30.txt). Is this in root of project or in src folder where source files are located?
I know these are beginner questions but I am stuck and need help.
EDIT:
As #Kane suggested I passed File and opened stream.
Instead of:
Scanner in = new Scanner(System.in);
I now use:
Scanner in = new Scanner(new File("alice30.txt"));
You can pass full file path in arguments (e.g. c:/.../alice30.txt))
The eclipse root directory is the base directory of the project (i.e., not the src/ directory, directly under the project.)
It's generally good style to have a 'resources' folder for txt, graphics, etc.
Rather than trying to pass a stream you could just pass the filename and open the stream yourself.
The reason what you're doing in Eclipse isn't working is because your command prompt/shell/dos/bash/whatever is handling creating the input stream out of the file for you. Eclipse doesn't do this. So, from the command line: < alice.txt means "run this program with no arguments, and create a stream to system.in", while doing that in Eclipse means "run this program with two arguments '<' and 'alice.txt'
you need do like this:
add:
import java.io.IOException;
import java.nio.file.Paths;
then:
replace"Scanner in = new Scanner(System.in);"to"Scanner in =new Scanner(Paths.get("alice30.txt"));" .
and you also need do this : "public static void main(String args[]) throws IOException "
With information from this link/page and several tries, I figure out a way to pass argument and file using the local route in eclipse Run -> Run Configurations.. , though it is not recommended as Kane said.
For my case: I need to do " $java someClass tinyW.txt < tinyT.txt " (This is an example from Algorithms book by Robert Sedgewick)
In my case, " tinyW.txt " is a argument, so in the eclipse environment, you can set in Run -> Run Configurations -> Arguments -> Program arguments: /local address/tinyW.txt. For my Ubuntu: /home/****/tinyW.txt
" < tinyT.txt " is a file that pipe to the main arguments, so you can set the route and file in " Run -> RUn Configurations -> Common ", click the "Input File", use the File System icon and select the file from local compute. See the figure. So in Input File: /local_address/tinyT.txt. My case is: /home/***/tinyT.txt. Hope it also works for you.

Categories