Cannot find symbol File - java

I'm working on a course project and using this code block my professor gave us to, one, get all files from the current directory and, two, to find which files are in the .dat format. Here is the code block:
// Get all files from directory
File curDir = new File(".");
String[] fileNames = curDir.list();
ArrayList<String> data = new ArrayList<String>();
// Find files which may have data. (aka, are in the .dat format)
for (String s:fileNames)
if (s.endsWith(".dat"))
data.add(s);
However, when I try to compile and test my program, I get this error message in response:
Prog2.java:11: cannot find symbol
symbol : class File
location: class Prog2
File curDir = new File(".");
^
Prog2.java:11: cannot find symbol
symbol : class File
location: class Prog2
File curDir = new File(".");
^
I admittedly have minimal experience with the File class, so it might be my fault entirely, but what's up with this?

Import the File class from the java.io.File package
i.e.
import java.io.File;
Here is documentation for java.io.File and a brief explanation of the File class.

Just add the following statement before the class definition:
import java.io.File;
If you use IDE, like Eclipse, JDeveloper, NetBeans, etc. it can automatilly add the import statement for you.

I think Naveen and Poodle have it right with the need to import the File class
import java.io.File;
Here is another method of getting .dat files that helped me, just FYI =)
It's a general file filtering method that works nicely:
String[] fileList;
File mPath = new File("YOUR_DIRECTORY");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
return filename.contains(".dat");
// you can add multiple conditions for the filer here
}
};
fileList = mPath.list(filter);
if (fileList == null) {
//handle no files of type .dat
}
As I said in the comments, you can add multiple conditions to the filter to get specific files. Again, just FYI.

Related

Why does File related stuff not Work? (Java)

Im currently writing a program which involves creating a Folder and a File within this Folder.
The first version worked, after that i decided to create a new project to give the code a clear form.
Now, suddenly the class creating the Files wont work anymore. I switched devices with the second project.
package com.company;
import java.io.*;
public class File {
File folder1 = new File("Data");
File file1 = new File("Data/MonData.txt");
//For both "Data" and "Data/MonData.txt it says
//"Expected 0 arguments but found 1"
public void DataText() {
if(folder1.exists()) { //exists = cant
} //resolve method
else {
folder1.mkdirs(); //mkdirs = cant
} //resolve method
if(file1.exists()) { //exists = cant
} //resolve method
else {
try {
file1.createNewFile(); //createNewFile = cant
} //resolve method
catch(IOException e) {
e.printStackTrace();
}
}
}
}
You should name your class in a different way. Naming your class File let java use it instead of java.io.File, so the method exists (and so the others) is not found because not in your class.
Your class name & importing class has same name File, So compiler check for your File class not java.io.File one which he should.
In case two class had same name, use java.io.File & your.File instead of File only
Both the classes of yours have the same name. Try naming the class File to java.io.File .
It should work fine
You can use fully qualified name
java.io.File folder1 = new java.io.File("Data");
java.io.File file1 = new java.io.File("Data/MonData.txt");

Correct path for reading lines of a file

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")

Inputting a text file into a program?

I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

Monitor folder for mp3

I have a homework to do and I don't know how to get started. I have to read from an external text file the paths of some random folders. I must make the paths for this folders available even I change the computer.
Then I have to output in the console the number of mp3 files found in every each folder.
My big problem is that I don't know how to make those paths work for every computer on which I run the program and also I don't know how the filter the content.
LATER EDIT: I've managed to write some code. I can search now for the mp3, but... can someone help me with this: how can i add a new path to the txt file from keyboard and also how can i remove an entire line from it?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String ext = ".mp3";
BufferedReader br = new BufferedReader(new FileReader("Monitor.txt"));
for (String line; (line = br.readLine()) != null;) {
findFiles(line, ext);
}
br.close();
}
private static void findFiles(String dir, String ext) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " No such folder folder");
File[] listFiles = file.listFiles(new FiltruTxt(ext));
if (listFiles.length == 0) {
System.out.println(dir + " no file with extension " + ext);
} else {
for (File f : listFiles)
System.out.println("Fisier: " + f.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FiltruTxt implements FilenameFilter{
private String ext;
public FiltruTxt(String ext){
this.ext = ext.toLowerCase();
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
I think that with "available even I change the computer" mean that you need to read the path from the file and not hard code it on your program so if you run in other computer you only need to change the text file and not the program.
But as #André Stannek had said in his comment, you must add to your question what have you tried and what is the exact programming problem you are facing.
When you face a problem, try to divide it in individual and more small problems. For example:
How to read a line from the console?
How to write a new line to a file?
Then try to search for a solution (if you can't think in one). For example in stack overflow, google and of course in the official documentation.
The official documentation:
http://docs.oracle.com/javase/tutorial/essential/io/index.html
Some questions in stackoverflow:
Read multiple lines from console and store it in array list in Java?
Read string line from console
How do I add / delete a line from a text file?
How to add a new line of text to an existing file in Java?
Or this links from Internet:
http://www.msccomputerscience.com/2013/01/write-java-program-to-get-input-from.html
This is the portal of the Java tutorials that you will found very useful when you are learning: http://docs.oracle.com/javase/tutorial/index.html

Java searching file name from the one folder

I am studying Java and I am not really sure the way to searching file. I would like to build the function which returning file names ( the files name should begin with star and end with .txt)
For example, in the folder we have Java source file with some file. For example, files:
1.txt
2.txt
4.txt
start.txt
star.txt
onstart.txt
starton.txt
myjava.java
Then I would like to get the start.txt, star.txt & starton.txt
I was looking for the FilenameFilter but I wasn't able to find to good way to find file. Does any one know the way to find files?
Probably the easiest way is to simple use File#listFiles(FileFilter), something like
File[] fileList = new File("/path/to/search").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});
// You'll need this import: import java.io.File;
File folder = new File("C:/Folder_Location");
// gets you the list of files at this folder
File[] listOfFiles = folder.listFiles();
// loop through each of the files looking for filenames that match
for(int i = 0; i < listOfFile.length; i++){
String filename = listOfFiles[i].getName();
if(filename.startsWith("Stuff") && listOfFiles[i].getName().endsWith("OtherStuff")){
// do something with the filename
}
}
File#getName() should return aString`, then use:
filename.startsWith(...);
filename.endsWith(...);

Categories

Resources