Correct path for reading lines of a file - java

I am new in Java and I have a question regarding the method readAlllines for the class Files. The file "Testfile.txt" is saved in the same directory as my Java class changeFiles. I want to read the lines out of it.
Here is my example code:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class changeFiles {
public static void main(String[] args) {
File temp =new File("Testfile.txt");
Path p = temp.toPath();
try{
List<String> zeilen = Files.readAllLines(p);
for(String line : zeilen){
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
Unfortunately, the method can't find the file. How do I get the correct path to my file in readAllLines?

You're trying to get file from working directory, check yours printing this in some way
System.getProperty("user.dir")
Place "Testfile.txt" there, run and enjoy.
Another solution will be put folder when reading file using File(folder, file) constructor:
// imagine your file is placed in: c:\tmp\Testfile.txt
final String folder = "C:\\tmp\\";
File temp = new File(folder, "Testfile.txt");
Or maybe merge both:
final String folder = System.getProperty("user.dir");
File temp = new File(folder, "Testfile.txt");

Java class location is not the same as current directory.
For example current directory is something like:
C:\Users\userName\project (This is where txt file shoud be)
And java class is something like C:\Users\userName\project\src\packageName\Java.java
to find out what the current directory is you can run: System.getProperty("user.dir")

Related

using File class to create new text file

Is there a way to use the File class to create a new text file? After doing some research, I tried:
import java.io.*;
public class createNewFile
{
public static void main(String args[]) throws IOException
{
File file = new File("newfile.txt");
boolean b1 = file.createNewFile();
}
}
...but there is still no newfile.txt in my source directory. It would also seem like there would be a void method to do this, instead of having to result to a boolean. Is there a way to do what I'm trying to do with the FIle class, or so I have to result to another class?
You have created a file but apparently not in your source directory but in the current working directory. You can find the location of this new file with:
System.out.println(file.getAbsolutePath());
One possibility to control the location of the new file is to use an absolute path:
File file = new File("<path to the source dir>/newfile.txt");
file.createNewFile();
You can try like this:
File f = new File("C:/Path/SubPath/newfile.txt");
f.getParentFile().mkdirs();
f.createNewFile();
Also make sure that the path where you are checking and creating the file exists.

Saving file to certain path (Java)

When I run this as a jar, this .properties file is created on the desktop. For the sake of keeping things clean, how can I set the path to save this file somewhere else, like a folder? Or even the jar itself but I was having trouble getting that to work. I plan on giving this to someone and wouldn't want their desktop cluttered in .properties files..
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class DataFile {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
prop.setProperty("prop1", "000");
prop.setProperty("prop2", "000");
prop.setProperty("prop3", "000");
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Since you are using the file name without a path, the file you creates ends in the CWD. That is the Current working directory the process inherits from the OS.
That is is you execute your jar file from the Desktop directory any files that use relative paths will end in the Desktop or any of it sub directories.
To control the absolute location of the file you must use absolute paths.
An absolute path always starts with a slash '/'.
Absolute path:
/etc/config.properties
Relative path:
sub_dir/config.properties
The simplest way is to hard code some path into the file path string.
output = new FileOutputStream("/etc/config.properties");
You can of course setup the path in a property which you can pass using the command line instead of hard coding it. The you concat the path name and the file name together.
String path = "/etc";
String full_path = "/etc" + "/" + "config.properties";
output = new FileOutputStream(full_path);
Please note that windows paths in java use a forward slash instead of back slash.
Check this for more details
file path Windows format to java format

Netbeans Java: Where to put my CSV file?

I followed a tutorial to create some simple code to output the contents of a csv file. However, I always get the following message:
java.io.FileNotFoundException: Data.csv (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at testing.csv.files.Test.main(Test.java:26)
BUILD SUCCESSFUL (total time: 0 seconds)
So I guess this means that the program is running, but it can't find my csv file. Basically, I just dragged and dropped it from my desktop into the "Source Packages" file in my Java Project, which is where my Test.java file is. I've also tried putting it in the "testing.csv.files", but that did not work either. Neither did putting it in the "Test Packages".
I've ran out of ideas. Where am I supposed to put this csv file?
here is my code:
package testing.csv.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) {
//.csv comma separated values
String fileName = "Data.csv";
File file = new File(fileName); // TODO: read about File Names
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data);
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You could try pointing to the full path of the file.
For example: String fileName = "Desktop/Data.csv";
FYI - You can copy the full path of a file by right clicking on a file while holding shift, then selecting: "copy as path".
Put your csv file(i.e Data.csv) in your project folder then it will work properly i tried your code it works fine for me

System cannot find the file

I am using the Scanner libraries to build a file reader, I have followed the outline in the Libraries and it compiles fine, but when I run it I get a FileNotFoundException : text.txt (The system cannot find the file specified). The file is located in the same folder as the .java file but it still says that it's not there.
Below is the code that I have any help would be great.
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
Scanner scanner = null;
try {
scanner = new Scanner(new BufferedReader(new FileReader("text.txt")));
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
}
}
Your file needs to be in the working dir of your runtime JVM. If you are not sure about that, you can do the following :
File file = new File(".");
System.out.println(file.getAbsolutePath());
You need to have the file in the same directory as your .class, not your .java. When compiling from an IDE the .class file usually gets placed in a build directory. Using the absolute path would also work, as Kevin suggested, or adding the file as a resource to a jar file and loading it as resource.
for debug purposes print canonical path of your file:
File file = new new File("text.txt");
System.out.println(file.getCanonicalPath());
so you can see where your file should be located

How to get the list of files under the directory in a JAR file

I want to know the list of files under the 'META-INF/config' directory in a JAR file.
I am using the below code to retrieve the files list. But it is failing.
Enumeration<URL> path = Thread.currentThread().getContextClassLoader().getResources("META-INF/config/");
while(path.hasMoreElements())
{
URL path1 = path.nextElement();
System.out.println("File =" +path1.getFile());
File configFolder = new File(path1.getPath());
File[] files = configFolder.listFiles();
for (File file : files)
{
System.out.println("\nFile Name =" + file.getName());
}
}
Can somebody help me in fixing this?
Thanks In Advance,
Maviswa
try below code
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import java.io.*;
public class JarContents{
public static void main(String[] args) throws IOException{
JarContents mc = new JarContents();
}
public JarContents() throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter jar file name: ");
String filename = in.readLine();
File file = new File(filename);
if(!filename.endsWith(".jar")){
System.out.println("Invalid file name!");
System.exit(0);
}
else if(!file.exists()){
System.out.println("File not exist!");
System.exit(0);
}
try{
JarFile jarfile = new JarFile(filename);
Enumeration em = jarfile.entries();
for (Enumeration em1 = jarfile.entries(); em1.hasMoreElements();) {
System.out.println(em1.nextElement());
}
}
catch(ZipException ze){
System.out.println(ze.getMessage());
System.exit(0);
}
}
}
Good Luck!!!
I remember having to do this a while back to read in a jar's manifest.mf to extract its version information to display. Given that all properly built jars have manifests, trying to access them as a resource is impossible (they all have the same path), and as such, had to examine the jar individually as a zip file.
Given that you aren't providing information as to where the failure is, it is difficult to guess as to what your problem is. I'm not sure if it is not finding the file that you are expecting, or if it is reading the wrong file, or if you are getting NPEs, etc.
try adding a "/" or "./" before the META-INF in the getResources() call
e.g.
...
read.currentThread().getContextClassLoader().getResources("./META-INF/config/");

Categories

Resources