I am using Scanner to read the File contents. For that I am using the following code.
public static void main (String[] args) throws IOException {
File file = new File("/File.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
System.out.print(sc.nextLine());
}
sc.close();
}
But this code always throws FileNotFoundException. I have tried Googling this, but I can't find where to check the file. Secondly, I have created files with same name in almost every directory to check when would the Code catch the presence of file.
You can see in the Package I have created a file named File.txt so that code can find it whereever it looks for.
In the Java docs, I get to know that the File accepts a String parameter as
File file = new File("file_name");
But what sort or what would be the param here, isn't told. Can I get the help?
I think you want File file = new File("File.txt"); instead of File file = new File("/File.txt");, get rid of the slash. If what you want is a relative path, you want .\File.txt
As #deterministicFail says in the comments, it is not a good idea to hardcode path separators, instead use System.getProperty("path.separator"); This way your code should work in multiple plataforms, so your code would be:
To make it plataform independent (Asuming you are using a relative path):
File file = new File("." + System.getProperty("path.separator") + "File.txt");
Replace the line
File file = new File("/File.txt");
with
File file = new File(".\\File.txt");
or
File file = new File("File.txt");
File f=new File("testFile.txt");
For this kind of referral you need to put file in root of your eclipse project (In parallel of src). This problem is only when you are Using Eclipse IDE.
Best solution for this kind of problems is checking AbsolutePath of the file
System.out.println(f.getAbsolutePath());
It will give you path where your code is looking for file.
There are two possibilities if you are looking for the file in the working directory then either use "File.txt" or "./File.txt". In case of windows one more option would be to use ".\File.txt).
If that is not what you are looking for, you can check which path the file refers to using either of the two sysouts immediately after instantiating the file, which will give you the absolute path on your machine.
File f = new File("/File.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getAbsoluteFile().getAbsolutePath());
I have never done it the way you did but this is how I read files.
This is the purpose of the class FileInpuStream. I use a buffer to get bytes.
If it is only a problem of path, why don't you simply use the complete path ? You can copy paste it from the file information.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// object I use to read files
fis = new FileInputStream(new File("File.txt"));
byte[] buf = new byte[8];
int n = 0;
// while there is something in the file
while ((n = fis.read(buf)) >= 0) {
for (byte bit : buf) {
// do what you want
System.out.print("\t" + bit + "(" + (char) bit + ")");
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Try not to use the / in File.txt, and if you really have to, use the backslash instead \ since you're in Windows
Related
I have been trying to get this method working for the past few days always coming back to the same problem. My file won't open unless the file path is specified and formatted.
This is my code:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
For some reason when I invoke the getAbsolutePath(), it gives me this path : "C:/Zaid/College/CE2336/Programs/File.txt"
whereas the file path that actually allows me to access the file is:
"C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
I don't understand what I should do to clean this up.
P.S. The MyImplementations is the package where the text file and my code reside in.
When you call
String filePath = new File(fileName).getAbsolutePath();
you are creating file in your root directory of the project and then getting that path instead of the file you already have and want to get
This should be sufficient in your case:
Scanner s = new Scanner(new File(fileName));
Also ensure when handling errors you share all the information you have: Print the file that was not found. You will see that this makes troubleshooting just so much easier.
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}
I am trying to delete and rename a file however the delete() and rename() function does not work. I can't seem to find the bug in the code as it should run properly by logic (i think). Can anyone tell me why it can't delete a fill. this code works except deleting old txt and renaming temp.txt to old file.
public Boolean deleteItem(String item){
try{
// creating and opening file
File f = new File("temp.txt");
f.delete(); // to delete existing data inside file;
File old = new File(file);
FileWriter writer = new FileWriter(new File("temp.txt"), true);
FileReader fr = new FileReader(old);
BufferedReader reader = new BufferedReader(fr);
String s;
// creating temporary item object
String[] strArr;
//searching for data inside the file
while ((s = reader.readLine()) != null){
strArr = s.split("\\'");
if (!strArr[0].equals(item)){
writer.append(s + System.getProperty("line.separator"));
}
}
//rename old file to file.txt
old.delete();
boolean successful = f.renameTo(new File(file));
writer.flush();
writer.close();
fr.close();
reader.close();
return successful;
}
catch(Exception e){ e.printStackTrace();}
return false;
}
The logic seems a little tangled. Here's what I think it looks like.
You delete file.txt
You create a new file.txt and copy 'file' into it
You delete 'file'
You rename file.txt to 'file'
You close input and output files
My guess would be that your operating system (unspecified) is preventing deletes and renames of open files. Move the closing to before the delete/rename. And check the return from those functions.
Aside: as a minor improvement to readability, you don't need to keep calling 'new File(xxx)' with the same xxx. A File is just a representation of the name of the file. Do it once. And 'File tempFile = new File("file.txt")' would be easier to follow than calling it 'f'.
Don't use the old java.io.File. It is notorious for its lax error handling and useless error messages. Use the "newer" NIO.2 java.nio.file.Path and the java.nio.file.Files methods that were added in Java 7.
E.g. the file.delete() method returns false if the file was not deleted. No exception is thrown, so you'll never know why, and since you don't even check the return value, you don't know that it didn't delete the file either.
The file isn't deleted because you still have it open. Close the files before attempting to delete+rename, and do it using try-with-resources, also added in Java 7.
Your code should be the following, through capturing exceptions and turning them into a boolean return value is error-prone (see issue with file.delete()).
public boolean deleteItem(String item){
try {
// creating and opening file
Path tempFile = Paths.get("temp.txt");
Files.deleteIfExists(tempFile); // Throws exception if delete failed
Path oldFile = Paths.get(file);
try ( BufferedWriter writer = Files.newBufferedWriter(tempFile);
BufferedReader reader = Files.newBufferedReader(oldFile); ) {
//searching for data inside the file
for (String line; (line = reader.readLine()) != null; ) {
String[] strArr = line.split("\\'");
if (! strArr[0].equals(item)){
writer.append(line + System.lineSeparator());
}
}
} // Files are flushed and closed here
// replace file with temp file
Files.delete(oldFile); // Throws exception if delete failed
Files.move(tempFile, oldFile); // Throws exception if rename failed
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Basically you want to remove selected lines from a text file.
The following code uses the stream API1. It filters out all the unwanted lines and writes the lines that you do want to a temporary file. Then it renames the temporary file to your original file, thus effectively removing the unwanted lines from the original file. Note that I am assuming that your "global" variable file is a string.
/* Following imports required.
import java.io.File
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
*/
Path path = Paths.get(file);
final PrintWriter[] pws = new PrintWriter[1];
try {
File tempFile = File.createTempFile("temp", ".txt");
tempFile.deleteOnExit();
pws[0] = new PrintWriter(tempFile);
Files.lines(path)
.filter(l -> !item.equals(l.split("'")[0]))
.forEach(l -> pws[0].println(l));
pws[0].flush();
pws[0].close();
Files.move(tempFile.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
finally {
if (pws[0] != null) {
pws[0].close();
}
}
1 Stream API was introduced in Java 8
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = new Scanner("inventory.csv");
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// ...
return size;
}
Here is the output I'm getting with no syntax errors.
Unable to open file inventory.csv.
considering it's in the same folder.
Same folder as what? inventory.csv was not present in the current working directory when you executed your program.
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.
In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here
You should try this
try{
FileReader fr=new FileReader(filename);
BufferedReader br =new BufferedReader(fr)
String lime=br.readLine();
br.close();
catch(Exeption e){}
I set up the method to try/catch this error. My issue is that it catches the fileNotFoundException for Trivia.txt even when I explicitly created Trivia.txt in the same package. I can't figure out why the file is not being found. I did some looking around for the answer to my problem, and had no luck. Anyway, here's my code
public static void readFile(){
try{
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
System.out.println();
}
catch(IOException e){
System.out.println("error reading file");
}
}
The code here is just a method of the TextHandler class that is called statically by WindowComp class (totally unrelated class). The package is mainPackage which holds the main() and WindowComp() and textHandler() alond with Triva.Txt
The way you open the file, it's supposed to be found in the current working directory, not in the subdirectory your source is found.
Try System.out.println(file.getCanonicalPath()) in order to find out where the code is expecting the file.
Try loading your file as a Resource, like this
URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());
This will load your file from the same package of the class who loads the resource.
You can also provide an absolute path for your file, using
URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");
If the file is found somewhere away from the current package of the class, you can also provide an absolute path directly to the constructor:
File file = new File("path/to/file/Trivia.txt");
You can also use a different constructor such as the one indicated in this answer:
Java - creating new file, how do I specify the directory with a method?
For further information, there's always the documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
I have a question about writing csv file on the current project in eclipse
public static void Write_Result(String Amount_Time_Dalta) throws IOException{
File file;
FileOutputStream fop = null;
String content = "";
String All_Result[] = Amount_Time_Dalta.split("-");
String path ="/Users/Myname/Documents/workspace/ProjectHelper/"+All_Result[1] + ".csv";
System.out.println(path);
content = All_Result[3]+ "," + All_Result[5] + "\n";
System.out.println(content);
file = new File(path);
fop = new FileOutputStream(file);
file.getParentFile();
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
}
and I am getting error which is
Exception in thread "main" java.io.FileNotFoundException: Invalid file path
at java.io.FileOutputStream.<init>(FileOutputStream.java:215)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at FileDistributor.Write_Result(FileDistributor.java:59)
at FileDistributor.main(FileDistributor.java:29)
I used
String path ="/Users/Myname/Documents/workspace/ProjectHelper/";
path to read a files. I was working fine.
However, when I am using same path to write result to file ( can be exist or not. I create or overwrite a file.) it returns Invalid file path.... I am not really sure why..
updated
just found interesting thing. when i just use File newTextFile = new File("1000".csv); then it is working. however, when i replace to File newTextFile = new File(filename +".csv"); it doesn't work.
What you have here is a valid path from which a File object can be created:
/Users/Myname/Documents/workspace/ProjectHelper/
But if you look at it a second time, you'll see that it refers to a directory, not a writable file. What's your file name?
What does your System.out.println say is the value of All_Result[1]?
Sample Code:
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args)
{
String[] array = {"1000.csv", "800.csv", "700.csv"};
File file;
FileOutputStream fop;
// Uncomment these two lines
//String path = "c:\\" + array[0];
//file = new File(path);
// And comment these next two lines, and the code still works
String path = "c:\\";
file = new File (path + array[0]);
// Sanity check
System.out.println(path);
try
{
fop = new FileOutputStream(file);
}
catch(IOException e)
{
System.out.println("IOException opening output stream");
e.printStackTrace();
}
if (!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
System.out.println("IOException opening creating new file");
e.printStackTrace();
}
}
}
}
In order to get this code to break, instead of passing array[0] as a file name, just pass in an empty string "" and you can reproduce your error.
I have encountered the same problem and was looking for answer. I tried using string.trim() and put it into the outputstream and it worked. I am guessing there are some trailing characters or bits surrounding the file path