I have a java program in a certain directory. I would like to make it find a list of all files that end with .dat or .DAT in the same directory as the program. Then I need to look at the first couple of lines of each file and parse a title string. The program should return an array of the file names, and an array of the first three lines of each file. I am pretty new to IO stuff, can anyone help?
Example: C:/my_directory/
Files: Program.class,
FOO.DAT (starts with "Lorem\nipsem\n$$0"),
bar.dat (starts with "ipsem\nLorem\n$$0")
Return: ["FOO.DAT","bar.dat"] and ["Lorem\nipsem\n","ipsem\nLorem\n"]
Thanks in advanced!
The following code snippet prints out all the files that have .dat or .DAT file extensions in a given directory. Try to figure out how you can read first three lines from a file. That must be fairly straightforward
File tmp = new File( "/tmp");
List<String> fileList = new ArrayList<String>();
if( tmp.isDirectory())
{
for( File f : tmp.listFiles())
{
if( f.isFile() )
{
if((f.getName().endsWith( ".dat") || f.getName().endsWith(".DAT")))
{
fileList.add( f.getName() );
}
}
}
for( String fileName : fileList)
{
System.out.println( fileName);
}
}
Related
I have the code below to find the List of files in a specified directory that have a particular word .
isWordPresent(word,filepath) method will give whether the word is contained in the path defined.
The code works absolutely fine until we have some folders inside the local drives.
Eg: String directoryName="D://FOLDER1"
I am not able to do the same , however, with local drives. All combinations of the following gace NullPointerException at //Code line C (as shown in the code snippet).
- String directoryName= "*D://*" OR String Directorypath = "*D:/*"
- String directoryName= "*D:\\*" OR String directoryName= "*D:\*"
( "D:\" would need an escape character, however, I have tried all combinations )
IMportantly, i tried replacing the code line A to:
`File[] roots = File.listRoots(); //code line A
if(Arrays.asList(roots).toString().contains(directoryName)){ //code line B`
where String directoryName = "C:\" and accordingly closed brackets.
The above changes worked until //Code line C where it showed NullpointerException
Is there a way i can access the D Drive?
`public void listFilesHavingTheWord(String directoryName,String word)
throws IOException{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles(); //code line A
//code line B
for (File file : fList){ //code line C
if (file.isFile()){
String filepath=file.getAbsolutePath();
if(isWordPresent(word,filepath)){
int index=file.getName().lastIndexOf(".");
if (index > 0) {
String fileNameWithoutExt = file.getName().substring(0, index);
System.out.println("word \""+word+"\" present in file--> "+fileNameWithoutExt);
}
}
} else if (file.isDirectory()){
listFilesHavingTheWord(file.getAbsolutePath(),word);
}
}
}`
When creating a new File object using
File directory = new File(directoryName);
directoryName needs to be a valid name. If it isn't directory.listFiles() returns null and you get the NPE on line C.
In your question you said you tried "*D://*" and various other variants all with wildcard characters (*) in them. This is not a valid file/directory name.
You need to provide a valid directoryName (without wildcards). So using just directoryName = "D:\\"; should work.
instead of providing manually you can use below code for all drive
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++){
System.out.println("drive: " + roots[i]);
//call listFilesHavingTheWord method here
}
and call listFilesHavingTheWord method here and pass parameter;
in this for loop, it will ist all drive one by one
I have a Java program that I am using to scan a directory to look for certain files. It finds the files but now I am trying to get the code to open the files once it finds them, but I am not sure how to do that.
Here a part of my code
File file = new File("/Users/******/Desktop/******");
String[] A = file.list();
File[] C = file.listFiles();
for (String string : A) {
if (string.endsWith(".txt")) {
System.out.println(string);
}
if (string.contains("******")) {
System.out.println("It contains X file");
}
}
I am trying to get it so once it finds the files ending in .txt, it opens all of them
I have tried using Google on how to solve his, I came across .getRuntime() and so I tried
try{
Runtime.getRuntime().exec("******.txt");
} catch(IOException e){
}
But I am not fully understanding how how this works. I am trying to get to so that once it finds the files it opens them. I am not trying to have the IDE open the text on the screen. I want the actual Notepad/TextEdit program to open.
File[] files = new File("/Users/******/Desktop/******").listFiles();
for (File f : files) {
String fileName = f.getName();
if (fileName.endsWith(".txt")) {
System.out.println(fileName);
}
if (fileName.contains("******")) {
System.out.println("It contains X file");
}
}
Can someone help me with reading a list of list of csv files. Like
List<List<File>> filesList;
Want to read through all the files contents in each list for processing, but unable to comeup with loop structure which can be used. Thanks.
UPDATE: I want to load files from each inner file list simultaneously. Like read first file from each inner list at a time, compare contents, then move to second file of a particular list and so on. Each inner list can be of variable size.
Here's an appropriate loop for this:
for (List<File> innerList : filesList)
for (File file : innerList)
// do something for a file
Alternatively you can use Iterator,like this
List<ArrayList<File>> filesList = new ArrayList<ArrayList<File>>();
//add objects to filesList here
Iterator<ArrayList<File>> filesListIterator = filesList.iterator();
while(filesListIterator.hasNext())
{
ArrayList<File> files = filesListIterator.next();
Iterator<File> filesIterator = files.iterator();
while(filesIterator.hasNext())
{
File file = filesIterator.next();
//do your own logic here;
}
}
Update
This may help you for compare
while(filesListIterator.hasNext())
{
ArrayList<File> files = filesListIterator.next();
for(int i=0;i<files.size()-1;i++)
{
File firstFile = files.get(i);//get a file
File secondFile = files.get(i+1);//get the next file
compareFiles(firstFile,secondFile);//this is your defined
//method for compare
}
}
List<List<File>> filesList;
for (List<File> list : filesList) {
for (File file : list) {
// your code here ...
}
}
Personally I would recommend using Google Guava if you can, this has a concat method
final List<List<File>> files = Lists.newArrayList();
for (final File file : Iterables.concat(files)) {
//doStuff with file
}
I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}
Now the idea in my mind id for this logic
1) construct the file name you want to use
2) open the file for write
3) each time you call a System.out.println(), make a similar call to write the same message to the file
4) when you are all done, make sure you close the file handle.
I have an rough idea something like this
try{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));
out.write("some information");
out.close;
}catch(IOException e){
e.printStackTrace();
}
please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console
As far as I can tell, this is the only thing you are actually asking:
Please advise how to that and the name of the file that is generated its name is to be based on timestamp. Lets assume that name of the output file would be 'output06282012' ...
The simple answer is:
String fileName = "output" + new Date().getTime();
You then go on to say:
.... and that text file should contain the same information that is shown on the console
You've got two choices:
You can change where System.out goes to by calling System.setOut(...). (Check the javadoc for details.)
You can create a PrintWriter or PrintStream wrapper for your file stream and write to that instead of writing to System.out.
In my opinion, it is a bad idea to use System.setOut(...) unless you've got no choice. It is a "global action" that affects the entire application. It is better to pass the writer that you want to use as a parameter ...
could you please sow in code as I have done that will clear the understanding
Sorry, I don't write people's programs for them (unless it is an interesting problem!). You need to write and debug the code yourself, using the information provided in the relevant javadocs. You can find the Java documentation online on the Oracle website: http://docs.oracle.com/javase/7/docs/
I am currently working on a project for school, it is Java based and I am using Eclipse on Linux Mint to write it. The assignment says use the statement String[] filenames = new java.io.File("icons).list(); to create an array of file names.
The problem is I am not sure what to do with this, I have spent the past few hours searching the Internet and my textbook, but to no avail. Does it need to be a separate method?
Below is my guess for the needed code in the model (the project is to make a matching game, with a GUI) the names will have to be converted later on into actual icons, but I am pretty sure I have that part figured out, I just can't seem to get the darn files into the array!!
Thanks in advance,
public String[] list() {
String[] fileNames = new java.io.File("icons").list();
return fileNames;
}
In Java, the File class does not necessary represent an "existing" file on the file system. For example:
File f = new File("some_unknown_unexisting_file.bob");
System.out.println(f.exists()); // most likely will print 'false'
Also, the class resolves the file from the current working directory. You may get this directory with
System.out.println(new File(".").getAbsolutePath());
In your case, if you can, I would suggest getting a File[] array with :
File[] files = new File("icons").listFiles(new FileFilter() {
#Override
public boolean accept(File f) {
return !f.isDirectory() && f.canRead();
}
});
for (File f : files) {
System.out.println(f.getAbsolutePath());
}
which will return an array of File objects which are not folders and that you can open for reading (note that this is not always true, but is just fine in your case).
But if you have to use list(), then this is equivalent :
File parent = new File("icons");
String[] fileStr = parent.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return !f.isDirectory() && f.canRead();
}
});
for (String f : fileStr) {
System.out.println(new File(parent, f).getAbsolutePath());
}
Also, with your list of files (String[]), you can create an icon using :
String filename = fileStr[i]; // some file name within the array
ImageIcon icon = new ImageIcon("icons" + File.separator + filename);
or with your list of files (File[]), it is cleaner :
File file = files[i]; // some file within the File[] array
ImageIcon icon = new ImageIcon(file.getAbsolutePath());
Good luck.
The code you wrote looks okay. Are you sure the folder "icons" exists where Java is looking?
Try this:
File f = new File("icons");
System.out.println("Does icons exist?" + f.exists());
System.out.println("Is it a dir?" + f.isDirectory());
System.out.println("How many files does it contain?" + f.list().length);
Good luck!
I've had the same problem. When I tried moving the icons folder into the folder just before the src folder, it seems to work. Not sure what I will do when I submit the assignment, as for it to work in JCreator, I believe it has to be with the .java files.