Resolving Path Differences Between Mac and Windows - java

I am new to Stack Overflow and fairly new to programming, so hopefully this makes sense. I am writing a java program that creates a file in a specific directory. My program works on Windows and creates a file in the right location, but it does not work on Mac. I have tried changing the backslashes to a single forward slash, but that doesn't work. How should I change the code so that it works for Mac or ideally for both? I've put some of the code below.
Thanks in advance!
Class that creates new path for file:
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
Method that gets user input on where to put file:
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}

you can use system properties to identify the system you are currently operating on ..
more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
but i would prefer using NIO. but that is your choice
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html

Forward slash "/" must be used to get the file path here. for ex.> Use:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();

Related

Java program file not found

I have looked through questions that have been posted here regarding this problem, and none of the solutions have been helpful. I found a link to this page http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.File%29
also, not helpful. I have looked through my text book, even copied a similar code straight from the book, and was again given the File Not Found Exception. The input.txt file is in the same folder as the program file, and I tried to use a specific path, also added this line to the code System.out.println(new File("C:/input.txt").getAbsolutePath());
it also did not help. I feel like I have more questions now than answers. The name of the file is correct, and case is correct. I did find that the .txt files are being saved in Word, so I went there and changed the format to plain txt file. Does it being saved as a Word document have something to do with this problem, or am I wasting time there?
Here is my code:
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class FileRead
{
public static void main(String[] args) throws IOException
{
double count = 0;
double sum = count++;
double average = sum/count;
File fileObject = new File("C:/input.txt");
System.out.println(new File("C:/input.txt").getAbsolutePath());
Scanner fileIn = new Scanner (fileObject);
while (fileIn.hasNext())
{
count = fileIn.nextDouble();
sum = count++;
}
average = sum/count;
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println("The total of the: " + count + "numbers entered are: "
+ sum + " and the average is: " + df.format(average));
}
}
C:/input.txt is telling the file system to look for a file called input.txt at the root of the hard drive, assuming C:/ is equivalent to C:\.
Is this where you are running the program in the root directory. If not, and there is no file called input.txt in the root director the program won't work as expected.
Try changing the the code as described by BlackCode, and/or removing the C:/
Typing pwd in a command window will tell you what directly you are in, and if its not the root of your hard drive the program can not find the file you are telling it too look for.
You need to escape the slash: "C://input.txt".
In file path change "/" to File.separator
Example:
File fileObject = new File("C:" + File.separator + "input.txt");
"The input.txt file is in the same folder as the program file": that means you only need "input.txt"
To see the files exactly with the names saved you can go to the command window and type dir at the location where you are looking for.
Alternately you can do that from within the program:
File f=new File(".");
String[] fs=f.list();
for(String s:fs) System.out.println(s);
If your file doesnt print then it's somewhere else.
Your code looks fine and it works fine on my Window 7 (although I had to change to administrator to create the c:\input.txt)
It is confusing that .getAbsolutePath() gives a value even if the file does not exist.
A better test is the following - it will print false if your file does not exist.
File fileObject = new File("c:/input.txt");
System.out.println(fileObject.exists());
Scanner fileIn = new Scanner (fileObject);
To be certain the file exists try this at the command line
echo 1 2 3 4 > input.txt
Then get rid of the full path and just use "input.txt" as the file name.
Use this :
Scanner fileIn = new Scanner ("C:/input.txt");

How do i make this File I/O Java program run in Unix?

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

Where to put a file to read from a class under a package in java?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}

Java cannot find a file existing on the server

In my Java Spring web app I am creating an image file. This file gets a temporary name and later on I try to rename it using:
public void rename(String productFilename){
String newProductFilename = "newfile.jpg";
File input = new File(imageDir + "/products/" + productFilename);
File output = new File(imageDir + "/products/" + newProductFilename);
Boolean checkRename = input.renameTo(output);
}
For creating the temp file, I'm using:
public String generate(){
String productFilename = "filename.jpg";
ImageIO.write(out, imageFileType, new File(imageDir + "/products/" + productFilename));
return productFilename;
}
the value of imageDir is: /var/images
Throughout the class, the imageDir variable is set to an absolute path. The strange thing is that this all works great on Windows, but when running on Linux, I get a FileNotFoundException.
I'm 100% sure that the file exists. Any clue on what I'm doing wrong?
I found the solution. The filenames needed to be trimmed to be recognised in Linux. This, however, worked without trimming in Windows.

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories