Hi I want to know how the program can locate a file.
For example. I have a class
public class MiReader {
private File file;
private BufferedReader bufferedReader;
public MiReader(String dir) {
try {
file= new File(dir);
bufferedReader = new BufferedReader(new FileReader(file));
} catch (Exception ex) {
Logger.getLogger(MiReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void imprimir() {
***
}
}
I know that the file is on the project (I'm using netbeans)
project is on C:\NetBeansProjects\Application
file: C:\NetBeansProjects\Application\file.txt
so when I instance MiReader must be something like this:
MiReader mr = new MiReader("C:\\NetBeansProjects\\Application\\file.txt");
and now if I run the program from another location
for example now its on
D:\Pograms\Application
so the file is D:\Pograms\Application\file.txt
and now I have to change the way I create the class to
MiReader mr = new MiReader("D:\\Pograms\\Application\\file.txt");
I want to know how the program can locate the file just running the program,
something like
MiReader mr = new MiReader(program.getLocation()+"\\file.txt")
Learning english :)
You could use relative paths. Aka
MiReader Mr = new MiReader("file.text");
This way the program will look for the file file.text inside the directory you run it from.
You can use System.getProperty to get the user.home, the user.dir, the classpath etc as a standard prefix for the file you are trying to open. Here are all of the System properties
ie
File f = new File (System.getProperty("user.home" + "/foo.txt"));
Related
I'm trying to read a basic txt file that contains prices in euros. My program is supposed to loop through these prices and then create a new file with the other prices. Now, the problem is that java says it cannot find the first file.
It is in the exact same package like this:
Java already fails at the following code:
FileReader fr = new FileReader("prices_usd.txt");
Whole code :
import java.io.*;
public class DollarToEur {
public static void main(String[] arg) throws IOException, FileNotFoundException {
FileReader fr = new FileReader("prices_usd.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("prices_eur");
PrintWriter pw = new PrintWriter(fw);
String regel = br.readLine();
while(regel != null) {
String[] values = regel.split(" : ");
String beschrijving = values[0];
String prijsString = values[1];
double prijs = Double.parseDouble(prijsString);
double newPrijs = prijs * 0.913;
pw.println(beschrijving + " : " + newPrijs);
regel = br.readLine();
}
pw.close();
br.close();
}
}
Your file looks to be named "prices_usd" and your code is looking for "prices_usd.txt"
There are a couple of things you need to do:
Put the file directly under the project folder in Eclipse. When your execute your code in Eclipse, the project folder is considered to be the working directory. So you need to put the file there so that Java can find it.
Rename the file correctly with the .txt extn. From your screen print it looks like the file does not have an extension or may be it's just not visible.
Hope this helps!
It is bad practice to put resource files (like prices_usd.txt) in a package. Please put it under the resources/ directory. If you put it directly in the resources/ directory, you can access the file like this:
new FileReader(new File(this.getClass().getClassLoader().getResource("prices_usd.txt").getFile()));
But if you really have a good reason to put it in the package, you can access it like this:
new FileReader("src/main/java/week5/practicum13/prices_usd.txt");
But this will not work when you export your project (for example: as a jar).
EDIT 0: Also of course, your file's name needs to be "prices_usd.txt" and not just "prices_usd".
EDIT 1: The first (recommended) solution does return a string on .getFile() which can not directly be passed to the new File(...) constructor when the application is built / not run in the IDE. Spring has a solution to it though: org.springframework.core.io.ClassPathResource.
Simply use this code with Spring:
new FileReader(new ClassPathResource("prices_usd.txt").getFile());
Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)
I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
This doesn't seem to create a file or folder. Why?
import java.io.*;
public class file1
{
public static void main(String[] args)
{
File text1 = new File("C:/text1.txt");
File dir1 = new File("C:/dir");
}
This one below does create a file.
import java.io.*;
public class file3
{
public static void main(String[] args)
{
try
{
FileWriter text1 = new FileWriter("C:/text.txt");
FileWriter dir = new FileWriter("C:/dir");
}
catch(Exception e){}
}
}
However, the directory seems to have a strange unusable icon.
What can I do to create a directory.
What are other simple methods to create files and folders.
Surprisingly, the File class does not represent a file. It actually represents a pathname for a file ... that may or may not exist.
To create a file in Java, you need to open it for output; e.g.
File text1 = new File("C:/text1.txt");
FileOutputStream os = new FileOutputStream(text1); // The file is created
// here ... if it doesn't
// exist already.
// then write to the file and close it.
or you could do this - new FileOutputStream("C:/text1.txt"). In both cases, an existing file will be truncated ... unless you use the FileOutputStream with a boolean parameter that says open for appending.
If you want to create a file without writing any data to it, you could also do this:
File text1 = new File("C:/text1.txt");
text1.createNewFile();
However, that will only create a new file if the file didn't already exist.
To create a directory in Java, use the File.mkdir() or File.mkdirs() methods.
UPDATE
You commented:
I tried File dir = new File("C:/dir1").mkdir(); it says incompatible types.
That is right. The mkdir() method returns a boolean to say whether or not it created the directory. What you need to write is something like this:
File dir = new File("C:/dir1");
if (dir.mkdir()) {
System.out.println("I created it");
}
Always READ THE JAVADOCS before using a method or class you are not familiar with!
A couple more things you need to know:
The best way to deal with the problem of making sure a file gets closed is to do something like this:
try (FileOutputStream os = new FileOutputStream(text1)) {
// now write to it
}
The stream os will be closed automatically when the block exits.
It is usually "bad practice" to catch Exception. It is always "bad practice" to catch Exception and do nothing in the handler. This kind of this hides the evidence of bugs, and makes your code unpredictable and hard to debug.
If you're creating a directory with File, you want this:
new File("C:/dir").mkdirs();
For creating directory you can use :
if(!text1.exists()){
text1.mkdir();
}
and for creating file use:
if(!text1.exists()){
try {
text1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
I am trying to createNewFile() in java.I have written down the following example.I have compiled it but am getting a run time error.
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String [] args)
{
try
{
File file = new File("home/karthik/newfile.txt");
if(file.createNewFile())
{
System.out.println("created new fle");
}else
{
System.out.println("could not create a new file");
}
}catch(IOException e )
{
e.printStackTrace();
}
}
}
It is compiling OK.The run time error that I am getting is
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFileExample.main(CreateFileExample.java:16)
some points here
1- as Victor said you are missing the leading slash
2- if your file is created, then every time you invoke this method "File.createNewFile()" will return false
3- your class is very platform dependent (one of the main reasons why Java is powerful programming language is that it is a NON-PLATFORM dependent), instead you can detect a relative location throw using the System.getProperties() :
// get System properties :
java.util.Properties properties = System.getProperties();
// to print all the keys in the properties map <for testing>
properties.list(System.out);
// get Operating System home directory
String home = properties.get("user.home").toString();
// get Operating System separator
String separator = properties.get("file.separator").toString();
// your directory name
String directoryName = "karthik";
// your file name
String fileName = "newfile.txt";
// create your directory Object (wont harm if it is already there ...
// just an additional object on the heap that will cost you some bytes
File dir = new File(home+separator+directoryName);
// create a new directory, will do nothing if directory exists
dir.mkdir();
// create your file Object
File file = new File(dir,fileName);
// the rest of your code
try {
if (file.createNewFile()) {
System.out.println("created new fle");
} else {
System.out.println("could not create a new file");
}
} catch (IOException e) {
e.printStackTrace();
}
this way you will create your file in any home directory on any platform, this worked for my windows operating system, and is expected to work for your Linux or Ubuntu as well
You're missing the leading slash in the file path.
Try this:
File file = new File("/home/karthik/newfile.txt");
That should work!
Actually this error comes when there is no directory "karthik" as in above example and createNewFile() is only to create file not for directory use mkdir() for directory and then createNewFile() for file.