i am trying to run a simple java program that reads from a file:
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
double prev = input.nextDouble(); // fencepost
for (int i = 1; i <= 7; i++) {
double next = input.nextDouble();
System.out.println(prev + " to " + next +
", change = " + (next - prev));
prev = next;
}
}
}
but i keep getting the following input:
Exception in thread "main" java.io.FileNotFoundException: weather.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at Files.test.main(test.java:9)
the file weather.txt is in the same folder as the .java program, and i am using eclipse kepler.
the file weather.txt is in the same folder as the .java program, and i
am using eclipse kepler.
src directory is for .java files. You should place weather.txt on project directory of Eclipse Kepler workspace.
If you put this line
System.out.println("current dir : " + System.getProperty("user.dir"));
just to see where the program is reading files from. You may then need to set the directory you are reading from relative to the class that is being run eg,
URL url = getClass().getResource("weather.txt");
File file = new File(url.toURI());
Eclipse Run Configuration allows you to set the directory where your program is running. Either set the directory accordingly, or use a path relative to the directory where you are running. This is usually the workspace directory.
Related
I am running java program from cmd like this java Main. But before that, I have to get to the route directory using cd ..., because my Main class is reding values from property file, which is in root directory. Is there a way or an option of setting the root directory, so then I will no need to get to this directory with cd commands ?
You could pass path to the directory as a parameter and get in from String[] args in main method. You'll pass absolute path to the file and it wouldn't be relevant from which directory you're starting your java process.
Here is the oracle's tutorial showing how you could do that.
Navigating to the directory through command prompt is very easy using a while loop and some simple String processing:
System.out.println("Please navigate to the desired directory then type 'done'...");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
StringBuilder path = new StringBuilder(); //Storage for dir path
path.append(System.getenv("SystemDrive"));
while(scanner.hasNextLine()) {
String command = scanner.nextLine(); //Get input
if(command.equalsIgnoreCase("done")) {
break;
}else if(command.startsWith("cd")){
String arg = command.replaceFirst("cd ", ""); //Get next dir
if(!arg.startsWith(System.getenv("SystemDrive"))) { //Make sure they are not using a direct path
if(!new File(path.toString() + "/" + arg).exists()) { //Make sure the dir exists
arg = arg.equalsIgnoreCase("cd") ? "" : arg;
System.out.println("Directory '" + arg + "' cannot be found in path " + path.toString());
}else {
if(arg.equals("..."))
path = new StringBuilder(path.substring(0, path.lastIndexOf("/"))); //StringBuilder#substring does not alter the actual builder
else
path.append("/" + arg);
System.out.println("\t" + path.toString()); //Add the dir to the path
}
}else { //If they are using a direct path, delete the currently stored path
path = new StringBuilder();
path.append(arg);
System.out.println("\t" + path.toString());
}
}else if(command.equalsIgnoreCase("dir")) {
System.out.println(Arrays.toString(new File(path.toString() + "/").list()));
//List the dirs in the current path
}else {
System.out.println("\t" + command + " is not recognized as an internal command.");
}
}
//Get your file and do whatever
File theFile = new File(path.toString() + "/myFile.properties");
You could use the -cp (classpath) command-line argument of Java.
Then if your directory structure is
<application folder>
|
|--config.props (properties file)
|
\--bin
|
|--Main.class
|
|... other classes
You could just go to the <application folder> and use java -cp bin Main to start the application. And it could refer to config.props as a file in the current folder (because it is in the current folder).
As this is something what you may not want to type all the time, it could be wrapped in a Windows .bat file or *nix .sh script, residing in , next to config.props.
I am trying to copy the files from one destination to another. I am unable to understand why the error occurs. Any help is appreciated.
public class FileSearch {
public void findFiles(File root) throws IOException {
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && iName.endsWith(".tif")) {
long fileSize = listOfFiles[i].length();
long sizeToKb = fileSize/1024;
File copyDest = new File("C:\\Users\\username\\Desktop\\ZipFiles");
if (fileSize <= 600000) {
System.out.println("|" + listOfFiles[i].getName().toString() + " | Size: " + sizeToKb+" KB");
FileUtils.copyFile(listOfFiles[i], copyDest);
}
} else if (listOfFiles[i].isDirectory()) {
findFiles(listOfFiles[i]);
}
}
}
I get the following error Exception in thread "main" java.io.IOException: Destination 'C:\Users\username\Desktop\ZipFiles' exists but is a directory
File srcFile = new File("/path/to/src/file.txt"); // path + filename
File destDir = new File("/path/to/dest/directory"); // path only
FileUtils.copyFileToDirectory(srcFile, destDir);
Try copyFileToDirectory(srcFile, destDir), you have to provide the source file absolute path with the file name, and the absolute path to the destination directory.
In addition, make sure you have write permission to copy the file to the destination. I am always on Linux system don't know how to achieve that, similarly you should be have Administrator privilege on Windows or some similar roles which is able to write files.
You want FileUtils.copyFileToDirectory(srcFile, destDir)
Why does the error occur? FileUtils.copyFile is used to copy a file to a new location. From the documentation:
This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.
Here, the destination exists, but is not a file; rather it is a directory. You cannot overwrite a directory with the contents of a file.
I'm trying check and see if my program is scanning in the contents of a File however get this error:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at lottery.main(lottery.java:40)
I don't see the problem as in my code as I always do my files this way, can't seem to understand to the problem.
Code:
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with the ticket data.");
String input = in.nextLine();
File file = new File(input);
in.close();
Scanner scan = new Scanner(new FileInputStream(file));
int lim = scan.nextInt();
for(int i = 0; i < lim * 2; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
System.out.println("Name " + name);
}
scan.close();
}
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. From docs.oracle.com
This means your FileInputStream wants an actual file system file provided. But you only made a filehandler when calling new File(). so you need to create the file on the file system calling file.createNewFile();
File file = new File(input); //here you make a filehandler - not a filesystem file.
if(!file.exists()) {
file.createNewFile(); // create your file on the file system
}
Scanner scan = new Scanner(new FileInputStream(file)); // read from file system.
Check if you start the jvm from the directory where the input file is located.
If not there is not possibility to find it with a relative path. Eventually change it to an absolute path (something like /usr/me/input.txt).
If the file is located on the directory where you start the java program check for the rights of the file. It could be not visible for the user launching the java program.
The problem is that your program could not find input.txt in the current working directory.
Look in the directory where is your program running and check it has a file called input.txt in it.
Below is the program that prints all the files & folders from the given path.
import java.io.File;
public class ListDirectoryRecursive{
public static void listRecursive(File dir){
if(dir.isDirectory()){
File[] items = dir.listFiles();
for(File item : items){
System.out.println(item.getAbsoluteFile());
if(item.isDirectory()){
listRecursive(item);
}
}
}
}
public static void main(String[] args){
/* Unix path is: /usr/home/david/workspace/JavaCode */
File dir = new File("C:\\Users\\david\\workspace\\JavaCode");
listRecursive(dir);
}
}
How do i make this java program run on Unix? What is the standard approach to make this program portable?
Edit: I guess, we know on any OS, user home directory is part of the environment setting with values like "c:\users\david" in windows and "/user/home/david" in Unix.
Take the directory as an argument via args:
File dir = new File(args[1]);
(checking of course that args.length is sufficient).
Then you can simply do
java ListDirectoryRecursive C:\Users\david\workspace\JavaCode
on Windows, and
java ListDirectoryRecursive ~david/workspace/JavaCode
on UNIX. This has the distinct advantage of allowing you use this program to list any directory, rather than being a hardcoded path.
Make the hardcoded absolute path C:\\Users\\david\\workspace\\JavaCode relative.
please dont harcode
File dir = new File("C:\\Users\\david\\workspace\\JavaCode");
use System.getProperty("user.home"); to get /usr/home/david or C:\Users\david\ directory
like
String path = System.getProperty("user.home") + File.separator + "workspace" + File.separator + "JavaCode";
File dir = new File(path);
thanks overexchange
I'm getting the following error
java.io.FileNotFoundException: in.txt, (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at FileTest.main(FileTest.java:50)
Yet Im certain that I have created a in.txt file under the src, bin, and root directory. I also tried specifying the full directory in my main parameters, but still not working. Why isn't Eclipse picking it up?
import java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
String inFileName = args[0];
String outFileName = args[1];
BufferedReader ins = new BufferedReader(new FileReader(inFileName));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
PrintWriter outs = new PrintWriter(new FileWriter(outFileName));
String first = ins.readLine(); // read from file
while (first != null) {
System.out.print("Type in a word to follow " + first + ":");
String second = con.readLine(); // read from console
// append and write
outs.println(first + ", " + second);
first = ins.readLine(); // read from file
}
ins.close();
outs.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
System.exit(1);
}
}
}
Given the error message, I would guess that Java is looking for the file name in.txt,, with a trailing comma.
I took your code and executed it with the following command-line params:
in.txt out.txt
It works with no problems at all. Check your command line.
By default, Eclipse will set the working directory to the project folder. If you have made changes to the settings, you can still find out the working directory by this simple line of code:
System.out.println(new java.io.File("").getAbsolutePath());
Put your text file in the folder printed, and you should be fine.
Put it in the project directory and if that doesn't work, the bin folder
Open your "Debug Configurations" and set, under the tab "Arguments", the Working Directory. Relative paths will be relative to the Working directory.
I created a new project Learning in my eclipse and put in.txt file inside a source directory . I tested using the sample java file .
public static void main(String[] args) {
File f = new File("a.txt");
System.out.println(f.getAbsolutePath());
}
Output:
/home/bharathi/workspace/Learning/a.txt
It looks in a project root directory . You can put in.txt inside a project's root directory or give the path until source directory .
There can be two problems:
In your console, the error shown with the ',' check -- >
java.io.FileNotFoundException: in.txt,
so probably JVM looks for a filename with the ','
The second case can be, You in.txt file is not in the right
location. Check whether it's is the Root of the project. or the main
path.
That would solve these types of problems.