I'm a Uni student trying to multiply two matrices stored in txt files via java and Eclipse. We were given a pre-compiled class file, but not the source code for the class file, essentially making it a blackbox class. We're supposed to use vim and the Linux terminal to program and execute our java code, but I find that Ecplise is far more time-efficient. However, when using the Linux terminal and vim my program works as intended, whereas when using Eclipse it does not.
Here's my source code with only the LOCs using the blackbox class
String fileOne = ArrayReader.getFileName("Enter the file name of matrix one");
int[][] matrixOne = ArrayReader.readArray(fileOne);
String fileTwo = ArrayReader.getFileName("Enter the file name of matrix two");
int[][] matrixTwo = ArrayReader.readArray(fileTwo);
The getFileName function outputs the argument, expecting the user to enter the file name (including the extension) of the file with the elements of the matrix in it. If it doesn't find the file, it returns an error message stating so, then asking for the file name again. The readArray function simply gets the elements and assigns them to the elements of the integer matrix.
I've tried putting the txt files in both my src and bin folders in my project directory, and inputting the file names with and without the file extension multiple times, but to no avail.
Any ideas?
I should put this in a comment but i don't have enough reputations
*Can you provide more details about the error so we can help and try to decompile the class to view it's source code you may find your answer also you can hardcode the file name (write it directly in the code) to test if everything works correctly *
The ArrayReader class expects the computer to be using Linux, not Windows.
Related
So I have a project, and this is one of the demands:
You should have a class named Project3, containing a main method.
This program reads the levels information from a file whose name is
specified as a command-line parameter (The file should also be
relative to the class-path as described here:)
All the file names specified in the levels and block definition files
should be relative to the class path. The reason we want them to be
relative to the class path is that later we will be able to read the
files from inside a jar, something we can not do with regular File
references.
To get an input stream relative to the class path (even if it's inside
a jar), use the following:
InputStream is =
ClassLoader.getSystemClassLoader().getResourceAsStream("image.png");
The idea is to keep a folder with files(definitions and images) and
then add that folder to the class path when running the JVM:
java -cp bin:resources ... If you don't add the resources folder to
you class path you wont be able to load them with the command from
above.
When run without parameters, your program should read a default level
file, and run the game accordingly. The location of the default level
file should be hard-coded in your code, and be relative to the
classpath_.
When run without parameters, your program should read a default level file, and run the game accordingly. The location of the default level file should be hard-coded in your code, and be relative to the classpath_.
The part of the code that handles the input is:
public Void run() throws IOException {
LevelReader level = new LevelReader();
List<level> chosenLevels = new ArrayList<>();
if (args.length >= 1) {
File f = new File(args[0]);
if (f.exists()) {
chosenLevels = level.makeLevel(args[0]);
}
}
if (chosenLevels.size() == 0) {
game.runLevels(defaultLevels);
} else {
game.runLevels(chosenLevels);
}
return null;
}
So my question is:
An argument should be the full path of a file which means:
D:\desktop\level3.txt
Is it possible to read a file from every location on my computer?
Because right now I can do it only if my text file is in the
project's directory (not even in the src folder).
I can't understand the rest of their demands. What does is mean "should be hard-coded in your code, and be relative to the
classpath_." and why is it related to InputStream method(?)
I'm confused all over this.
Thanks.
A classpath resource is not the same as a file.
As you have correctly stated, the full path of a file is something like D:\desktop\level3.txt.
But if ever want to distribute your application so it can run on other computers, which probably won’t have that file in that location, you have two choices:
Ask the user to tell the program where to find the file on their computer.
Bundle the file with the compiled program.
If you place a non-.class file in the same place as .class files, it’s considered a resource. Since you don’t know at runtime where your program’s class files are located,¹ you use the getResource or getResourceAsStream method, which is specifically designed to look in the classpath.
The getResource* methods have the additional benefit that they will work both when you are developing, and when the program is packaged as a .jar file. Individual entries in a .jar file are not separate files and cannot be read using the File or FileInputStream classes.
If I understand your assignment correctly, the default level file should be an application resource, and the name of that resource is what should be hard-coded in your program. Something like:
InputStream is;
if (args.length > 0) {
is = new BufferedInputStream(
new FileInputStream(args[0]));
} else {
// No argument provided, so use program's default level data.
is = ClassLoader.getSystemClassLoader().getResourceAsStream("defaultlevel.txt");
}
chosenLevels = level.makeLevel(is);
¹ You may find some pages that claim you can determine the location of a running program’s code using getProtectionDomain().getCodeSource(), but getCodeSource() may return null, depending on the JVM and ClassLoader implementation, so this is not reliable.
To answer your first question, it doesn't seem like they're asking you to read from anywhere on disk, just from within your class path. So that seems fine.
The second question, "What does is mean 'should be hard-coded in your code, and be relative to the classpath'?". You are always going to have a default level file in your project directory. Define the path to this file as a String in your program and that requirement will be satisfied. It's related to the InputStream because the stream requires a location to read in from.
I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.
I'm working on a program that is supposed to take two files as command line arguments, open the files, and read data from the files to make a data structure.
So far, I have been able to make the structure using File() to open the files and Scanner to read the data. The problem is that I have been providing a specific path to the call for File like this
File f1 = new File("F:/MinSpan/resources/cities.txt");
Scanner sc1 = new Scanner(f1);
I don't think this is going to work for the person who tries to run this program, because I have provided the path for where my specific txt files are located - they're on my flash drive (F) and in some folders. Is there a way I can program this to pass some kind of args[] value in for File() based on the cmd arguement the user has provided?
I have already tried just doing new File(args[2]) , and it can't find the file because there is no path.
The reason for that is because, if you are passing in only two paths, args[2] wont return anything, because args[] starts at 0. So you'd want to use:
new File(args[0]);
new File(args[1]);
Does that make sense?
If you're going for something like java -jar program.jar FILE, then have the program check for the String in args[] at index 0.
Then, construct your file. Check if the file exists (in java.io, it's File.exists()) and return an error message to the user if it's wrong.
I am running OSX 10.11 with IntelliJ 14.1.15.
I have a programme which takes a txt file as an argument. I can run it from the terminal through java SearchCmd test.txt and then it allows me to enter a search term and searches that list.
How do I do this from within IntelliJ, so that I can click the run button and it reads the file and I am able to enter a search term in the IntelliJ console.
The main class 'SearchCmd' contains the main method, as such:
public class SearchCmd {
public static void main (String[] args) throws IOException {
String name;
// Check that a filename has been given as argument
if (args.length != 1) {
System.out.println ("Usage: java SearchCmd <datafile>");
System.exit (1);
}
// Read the file and create the linked list
HTMLlist l = Searcher.readHtmlList (args[0]);
}
However, when I try and run this it says: "Usage: java SearchCmd ".
In order to pass the test.txt file to IntelliJ, I entered the file path in the 'Run/Debug Configurations'.
Sadly I can't attach the picture. :-(
Any help on fixing this and helping me run it from IntelliJ will be greatly appreciated.
Go to Run -> Edit Configurations, Select Application, then give the main class name and program arguments. Then Run.
I just figured it out.
So instead of pasting in an absolute path, you need to paste a relative path from the root directory of your IntelliJ project. And most importantly you have to ommit the initial forward slash.
So my absolute path to the file might be this:
Computer/project/TestInput/itcwww-small.txt
But the path that I need to put into Programme Arguments is:
TestInput/itcwww-small.txt
I hope that this will help someone else.
I had the same issue and was very confused with the previous answers of this question, so here is my explanation to anyone that is lost like I was.
With the project open.
Run > Edit Configurations....
Add the whole directory that the file is in it on the Program
Arguments field with the file format at the end.
Steps to follow-
1. Run->Edit Configurations.
2. Select Application.
3. Provide main class name and command line arguments and apply.
4. Run
Adding the input file name's relative path in the "Program Arguments" will allow the "main" method reading the argument in as a "String"
However, in order to actually let the System to understand using data from the file as standard input, it seems we have to specifically read the file and set the input stream as the system input :
try {
FileInputStream inputStream = new FileInputStream(new File(args[0]));
System.setIn(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You need to go in the menu Run -> Edit configurations.
Select your configuration and add the parameters in the field Program arguments
The field Program arguments is what appears after the class name from command line. For example:
java MyMainClass ProgramArgument1 ProgramArgument2 ProgramArgument3
in your example
java SearchCmd test.txt
the program argument is test.txt
Note: Use an absolute path or check that the working directory is the directory containing your file
I know that you must add command line arguments into the "Run Configurations" in Eclipse to get your command line arguments to be passed every time by default. This worked fine on my PC.
The purpose of this question is to create a simple program that can be submitted to an online programming challenge site (like codeeval). The system provides a file path to the command line args[0] and then you manipulate the file and its data.
On the PC I had my Class folder > Default Package > (file.txt and TestCode.java)
The project was set up with a run configuration with simply file.txt in the program arguments section.
On the MAC this doesn't seem to be working. I get a fileNotFoundExcepion. I'm new to MAC so I'm thinking this might be a problem with file extensions not being what I think they are. I saved a file as "file.txt" but if I save it as "file" MAC doesn't show the file extensions and I'm not sure if MAC supports .txt by default.
If it doesn't support .txt, what file type is a "text document"? I tried saving the text document as "file" leaving off any extension, and then adding file.rtf or file.txt or even file to the Program arguments and none of that works. It all gives me a fileNotFoundException.
EDIT
The intent is to be able to develop solutions to the CodeEval (or similar) website and submit them. I have previously solved many problems on CodeEval and turned them in with the code below from a PC. This, however, doesn't work on MAC. The answer involving the use of the URL does not work when run from the solution checking platform (presumably because the program is not actually saved onto the system).
EDIT 2
My entire program:
public class TestCode {
public static void main (String[] args)throws IOException{
File filename = new File(args[0]);
Scanner file = new Scanner(filename); // returns the fileNotFoundException
while( file.hasNextLine()){
String line = file.nextLine();
System.out.println(line);
}
}
}
Under "Run Configurations" in the Arguments tab > Program Arguments I have tried putting file, file.txt, file.rtf all three with a "text document" in the same directory as the above program. I have tried naming that file file, file.txt and file.rtf And i tried every combination of these names.
Did you try to use the absolute file name as command line parameter? This should be something like /Users/name/path/to/your/file. If the file is part of your project, you can also use a variable such as ${project_loc}/file (try the button Variables… below the Program Arguments field.
Replace your code with this
URL resource = TestCode.class.getResource(args[0]);
Scanner file = new Scanner(new File(resource.getFile()).getAbsoluteFile());