Reading all files in directory
Hi
I need to read all the files inside a directory where my app resides. I have the following:
File file = new File(args[0]);
Reader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
This works fine for one file, but i have many files I would like to
read in this directory. I was hoping I could just do:
java MyApp *
but it doesn't work. thanks in advance for any help.
J.
rtfm
http://java.sun.com/products/jdk/1.1/docs/api/java.io.File.html#list()
Similar Messages
-
Reading all files on directory using "utl_file" package...
I need to read all files in directory via PL/SQL. I don't know
name files (are data dynamics create for automation system),
only I know your extensions.
Can I do this using the package "utl_file" or I need to create
program in another language (C, C++, for example)?
Any ideas...
Thanks.Hi,
you can't do that with the UTL_FILE package (it can't retrieve
file names).
A very simple solution would be, if you created on OS-level a
file which contains the filenames of directory and then read this
file using UTL_FILE. With the information on all file names you
can enter a loop which opens and reads all files again using
UTL_FILE.
A more mundane solution could be to use the features on the iFS.
Cheers
Gerald -
Use JFilechooser to read all Files inside Directory
Hello gang!
I was wondering how to modify the code below to allow it to select Files AND Directories. If it selects a Directory, I want it to be able to look in that directory for all .jpg files, and return a list of all the jpg files to me. It does not have to search in any subfolders..only the folder that the user selects with the jfilechooser.
File defaultDirectory = new File("C:\\"); // Set Default Directory
JFileChooser fc = new JFileChooser( defaultDirectory );
fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
fc.setAccessory(new ImagePreview(fc));
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showDialog(currentFrame, "Attach");
if (returnVal == JFileChooser.APPROVE_OPTION)
File files[] = fc.getSelectedFiles();
for (int b=0; b < files.length; b++)
String pathName = files.getAbsolutePath();
storeInfoRef.setFiles(pathName);
defaultDirectory = files[0];
fc.setCurrentDirectory( defaultDirectory ); // New Default Dir
else
{ System.out.println("Attachment cancelled by user"); }I have solved my problem. For anyone with a similar problem here is the code I added since my last post
JFileChooser fc = new JFileChooser( defaultDirectory );
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
fc.setAccessory(new ImagePreview(fc));
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showDialog(currentFrame, "Attach");
if (returnVal == JFileChooser.APPROVE_OPTION) //If Button Pressed
File files[] = fc.getSelectedFiles(); // Get Users Selections
for (int b=0; b < files.length; b++) // For Each Selection
if ( files.isDirectory() ) // If User Selected a Directory
File[] folderFiles = files[b].listFiles(); // Get contents of folder
log.append("For folder: " + files[b].getName() + "." + newline);
int count=0; // Keeps Count of # of Image Files
for ( int i=0; i < folderFiles.length; i++ ) // For each item in folder
if( (folderFiles.getName().endsWith(".jpg") ) || //If file is an Image
(folderFiles[i].getName().endsWith(".jpeg")) ||
(folderFiles[i].getName().endsWith(".bmp") ) ||
(folderFiles[i].getName().endsWith(".gif") ) ||
(folderFiles[i].getName().endsWith(".tif") ) ||
(folderFiles[i].getName().endsWith(".tiff") ) )
System.out.println( folderFiles[ i ].getName() );
String pathName = folderFiles[i].getAbsolutePath(); //Get Path of File
storeInfoRef.setFiles(pathName); //Save Path of File
log.append(" Attaching file: " + folderFiles[i].getName() + "." + newline);
count++; //Increase Counter
if ( count == 0 ) // If No Images
log.append( " There are no Image Files to Attach" );
else if ( files+.isFile() ) // If User Selected File(s)
String pathName = files[b].getAbsolutePath();
storeInfoRef.setFiles(pathName);
System.out.println ("File Size: " files[b] +" is "+files.length() );
log.append("Attaching file: " + files[b].getName() + "." + newline);
defaultDirectory = files[0];
fc.setCurrentDirectory( defaultDirectory ); // New Default Dir
else
{ log.setText("Attachment cancelled by user." + newline); } -
How to read a files in directory and its subdirectories
I wants to read all files in directory, its subdirectory and further till end the files in the subdirectory of subdirectories.
I have some idea the I can do this by using recursive function, using the functions isDirectory(), File.list() etc.
How much you can please help me. (via code of logic)import java.io.*;
import java.net.*;
public class MyCon
public static void main(String args[]) throws
IOException
File file=new File("c:/");
openDirectory(file,"");
System.in.read();
static void openDirectory(File file,String indent)
String[] string=file.list();
String path=file.getAbsolutePath();
for(int i=0;i<string.length;i++)
File temp=new File(path+"/"+string);
if(temp.isDirectory())
openDirectory(temp,indent+" ");
else
System.out.println(indent+temp.getName()); -
How to read all files under a folder directory in FTP site
Hi Experts,
I use this SQL to read data from a file in FTP site. utl_file.fopen('ORALOAD', file_name,'r');
But this need to fixed file name in a directory. However, client generate output file with auto finename.
SO do we have any way to read all file by utl_file.fopen('ORALOAD', file_name,'r');
We need to read all file info. because client claim for security issue and does not to overwirte output file name,
we must find a way to read all file in output directory.
Thanks for help!!!
JimIf you use Chris Poole's XUTL_FTL package, I believe that contains functions that allows you to query the directory contents.
http://www.chrispoole.co.uk/apps/xutlftp.htm
Edited by: BluShadow on Jan 13, 2009 1:54 PM
misread the original post -
HTML Parsers and reading all files in a directory
Hello all,
I was wondering if there was a html parser included in java. I am writing a program where I want to be able to search all the files in a directory tree for a particular string. I was able to read one file in a single directory but not in any other directory. How would I go about writing code to be able to access all files in directory that has multiple sub folders.
Also, when I started to write my program I tried to use the DOM XML Parser to parse my html page. My logic behind this decision was that if you look at html code it is an xml document. But as I was trying to run my program I noticed that I had to convert my html document into xml format. I really don't want to have to build my own html parser. Is there a html parser that is included in Java. Oh my program is just your basic text program. No interfaces.
Thanks for any help that you can provide
Hockeyfana particular string. I was able to read one file in
a single directory but not in any other directory.
How would I go about writing code to be able to
access all files in directory that has multiple sub
folders.
You can do that several ways.
Most likely you'll end up with some sort of recursive iteration over the directory tree.
Not hard to write, somewhat harder to prevent memory problems if you end up with a lot of data.
Also, when I started to write my program I tried to
use the DOM XML Parser to parse my html page. My
logic behind this decision was that if you look at
html code it is an xml document. But as I was
trying to run my program I noticed that I had to
convert my html document into xml format. I really
don't want to have to build my own html parser. Is
there a html parser that is included in Java. Oh my
program is just your basic text program. No
interfaces.
A VALID xhtml document is a valid XML document.
Problem is that most HTML isn't xhtml.
Another problem is that most HTML is fundamentally broken even to its own standards (which have always been based on SGML on which XML is also based).
Browsers take that into account by being extremely lax on standards compliance and effectively making up tags as they go along to fill in the missing ones in the trees they parse.
That's however not a standardised process and each browser handles it differently (and as a result most html will render differently in different browsers).
Java contains a simple HTML parser in Swing, but it's primitive and will only parse a subset of HTML 2.0.
There are almost certainly 3rd party libraries out there that can do better, both free and/or commercial. -
Read all files in chield and their chield's directory
I am trying to make a program which read all files in a directory and its subdirectory like scandisk program of window's operating system. I gause this I can do via recursion using the methods isDirectory(), File.list() etc. Please help me to implement this problem in code.
Regards
yogeshyou guys should collaborate,
http://forum.java.sun.com/thread.jsp?forum=4&thread=153110&start=0&range=30#443719 -
How to Read all files inside resource Folder inside Jar?
I have a Jar file,,,, The program reads for resource files in the resource folder inside the Jar. I want my program to read all files inside this folder without knowing the names or the number of files in the folder.
I am using this to make an Applet easy to be updated with spicific files. I just want to add a file inside the resource folder and Jar the program and automatically the program reads what ever is in there!!
I used the File class to get all file names inside the resource folder. it works fine before Jarring the program. After I jar I recieve a URI not Herarichy Exception!!
File fold=new java.io.File(getClass().getResource(folder).toURI());
String[] files=fold.list();
I hope the question is clear!!How to get the directory and jar file that you class resides in:
// returns path and jarfile (ex: /home/mydir/my.jar)
public String getJarfileName()
// Get the location of the jar file and the jar file name
java.net.URL outputURL = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
String outputString = outputURL.toString();
String[] parseString;
int index1 = outputString.indexOf(":");
int index2 = outputString.lastIndexOf(":");
if (index1!=index2) // Windows/DOS uses C: naming convention
parseString = outputString.split("file:/");
else
parseString = outputString.split("file:");
String jarFilename = parseString[1];
return jarFilename;
}If your my.jar was in /home/mydir, it will store "/home/mydir/my.jar" in jarFilename.
note: getLocation returns "file:/C:/home/mydir/my.jar" for Windows/DOS and "file:/home/mydir/my.jar" for windows, thus why I look for the first and last index of the colon so I can correctly split the string.
If you want to grab a file in the jar file and get an InputStream, do the following:
import java.io.*;
import java.util.Enumeration;
// jar stuff
import java.util.jar.*;
import java.util.zip.ZipEntry;
public class Jaris
private JarFile jf;
public Jaris(String jarFilename) throws Exception
try
jf = new JarFile(jarFilename);
catch (Exception e)
jf=null;
throw(e);
public InputStream getInputStream(String matchString) throws Exception
ZipEntry ze=null;
try
Enumeration resources = jf.entries();
while ( resources.hasMoreElements() )
JarEntry je = (JarEntry) resources.nextElement();
// find a file that matches this string from anywhere in my jar file
if ( je.getName().matches(".*\\"+matchString) )
String filename=je.getName();
ze=jf.getEntry(filename);
catch (Exception e)
throw(e);
InputStream is = jf.getInputStream(ze);
return is;
// for testing the Jaris methods
public static void main(String[] args)
try
String jarFilename=getJarfileName();
Jaris jis = new Jaris(jarFilename); // this is the string we got from the other method listed above
InputStream is=jis.getInputStream("myfile.txt"); // can be used for xml, xsl, etc
catch (Exception e)
// this is just a test, so we'll ignore the exception
}Happy coding! :)
Doc -
Newbie question - How to read all files for a backup
Hello all,
I have two users on my iMac. I am an administrator and the other user is a Standard user.
From my account, I wish to run backup software that will backup the entire "User" directory. The problem I am having is that when I run the backup software (fyi: iBackup),
it complains that it cannot read the files in the other user's account.
I notice that when I browse to the other user's account, all the directories in their home folder are locked.
How can I run my backup software so that it can read all files in the User directory?
Thank you kindly!
Jeff
17" iMac Core Duo Mac OS X (10.4.6)Hi kneecarrot !
I don't know if this will suit your needs, but one easy way of backing up other user's stuff is via the terminal . If you have an admin accountm just use:
sudo ditto -rsrcFork /Users /Volumes/"nameof_anotherharddrive"/Users
This will perform an identical clone of all your users home direcories for backup purposes. To restore the bkd'up files, just reverse the lines:
sudo ditto -rsrcFork /Volumes/"nameof_anotherharddrive"/Users /Users
ATTENTION: Be aware that it will restore the files to the exact structure and contents it was when backed up, erasing all new and modified files!! You may however copy just the files/folders you want to recover, e.g.:
sudo ditto -rsrcFork /Volumes/"nameof_another_harddrive"/Users/"usera"/Documents /Users/"user_a"/Documents
IMPORTANT: As with all terminal commands... be careful, think twice and double-check the syntax. You may want to test with non-critical stuff or demo user accounts first.
Good luck,
Michael
MacBook Pro Mac OS X (10.4.6) 2 Gig RAM -
How to delete a READ ONLY file from Directory
Hi Friends,
how to delete a READ ONLY file from Directory , file is in my system only.
Please help me .
note: its read only file.
Thank you.
Karthik.hI,
try with this statement.
delete dataset <datasetname>.
this will definitely work.
Regards,
Nagaraj -
Read all Files from a Folder on Server
Hi,
Can anyone help me in finding if there's any way to read all files in a folder on the server?Any Function module or anything.
ThanksOn App server? Try this sample program.
report zrich_0001 .
data: begin of itab occurs 0,
rec(1000) type c,
end of itab.
data: wa(1000) type c.
data: p_file type localfile.
data: ifile type table of salfldir with header line.
parameters: p_path type salfile-longname
default '/usr/sap/TST/DVEBMGS01/data/'.
call function 'RZL_READ_DIR_LOCAL'
exporting
name = p_path
tables
file_tbl = ifile
exceptions
argument_error = 1
not_found = 2
others = 3.
loop at ifile.
format hotspot on.
write:/ ifile-name.
hide ifile-name.
format hotspot off.
endloop.
at line-selection.
concatenate p_path ifile-name into p_file.
clear itab. refresh itab.
open dataset p_file for input in text mode.
if sy-subrc = 0.
do.
read dataset p_file into wa.
if sy-subrc <> 0.
exit.
endif.
itab-rec = wa.
append itab.
enddo.
endif.
close dataset p_file.
loop at itab.
write:/ itab.
endloop.
Regards,
Rich Heilman -
Read All files in folder and sub folder
Hi,
i can read files in a folder,but not in a sub folders.can any one give me idea to read all files in the folder and its sub folder.
DeepanHi
This code may help you
Bliz
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class CountFiles {
* @param args
* @throws IOException
* Count files in <path> and all its subDirs
public static String path = "c:";
public static String src1 = "";
public static FileChannel channel;
public static int numF;
public static int numD;
public static void main(String[] args) throws IOException {
countFiles(path);
System.out.println("Number of files :\t"+numF);
System.out.println("Number of dirs :\t"+numD);
public static void countFiles(String strPath) throws IOException
File src = new File(strPath);
if (src.isDirectory())
numD++;
String list[] = src.list();
try {
for (int i = 0; i < list.length; i++)
src1 = src.getAbsolutePath() + "\\" + list;
File file = new File(src1);
try {
channel = new RandomAccessFile(file, "r").getChannel();
}catch(java.io.FileNotFoundException e){}
countFiles(src1);
}catch(java.lang.NullPointerException e){}
else
numF++; -
I need to compare the date of creation of multiple files that are being created throughout the execution of the application, so that if the date and time of the file is equal to the current date and time, a led will light up, and if not, the file will be deleted.
I've made a VI, but I'm getting an error and I don't know how to fix it.
What I need is for the vi to read all the files in the directory and continue reading all the files as they are created in the directory. The weird thing about this error is that it only shows up when I run it without highlight execution.
Attachments:
Date & Time comparison.vi 10 KBSeveral things come to mind.
0. What error do you get? The error code or description can be very useful in identifying a problem.
1. When a VI runs OK with execution highlighting and fails without, that usually indicates a timing problem.
2. The inner loop runs as fast as possible because there is nothing in there to slow it down. Put a Wait (ms) in there to slow things down a bit.
3. The loops will never stop. Do not create infinite loops by wiring False constants to the Stop if True terminal. The inner loop should probably be a for loop which will automatically stop after checking all files. The outer loop should have something to stop it - a front panel button, error, something.
4. The timestamp has approximately 19 digits of precision in the fraction of a second portion. The resolution is limited by the clock in the computer. The implication is that you will almost never get exact equality. You need to define "how close" is close enough. Perhaps within 1 second? Then modify the comparison function to determine whether the timestamps are within that limit.
Lynn -
Hi All,
My requirment is to get releted files from Local Directory.
For Example Path is "D/Data/"
in this path there is files like
abc123_de.txt
abc123_en.txt
xyz123_de.txt
abc123_pt.txt
xyz123_en.txt
pqr123_en.txt
bcg234_en.txt
sjd467_en.txt
Now i want to use only files which are strart from abc123 and use their data.
From which FM i can do it or how can i do this?
Thanks,
MahipalsinhDear Mahipalsinh,
I have got the same requirement some days back, i think there is no FM for your requirement. so what i did, i have get all the files using below FM and Concatenate the ABC.
Please use the Below FM, because if the file name is above that 50 character that time always it gives the full file name. Please check, if u used the other one for getting the Files.
CALL FUNCTION 'EPS2_GET_DIRECTORY_LISTING'
EXPORTING
iv_dir_name = lv_dir_name
TABLES
dir_list = lt_file_name
EXCEPTIONS
invalid_eps_subdir = 1
sapgparam_failed = 2
build_directory_failed = 3
no_authorization = 4
read_directory_failed = 5
too_many_read_errors = 6
empty_directory_list = 7
OTHERS = 8.
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.
For reading Specific Files.
CONCATENATE 'AP' lv_internal_date INTO lv_filename.
LOOP AT lt_file_name INTO ls_file_name.
lv_index = sy-tabix.
IF ls_file_name-name CS lv_filename.
" PUT YOUR LOGIC
endif.
endloop.
Thanks,
Nishant -
Can i delete ALL files in directory ?
i create a upload test using FileReference & PHP.
In this scenario user upload files to http server.
Now how can i delete all files in /files/uploads folder in AS3
AS3 Code:
req = new URLRequest();
req.url = ( stage.loaderInfo.parameters.f )? stage.loaderInfo.parameters.f : "http://www.website.com/test/upload.php";
uploadFile = new FileReference();
select_btn.addEventListener( MouseEvent.CLICK, browse );
uploadFile.addEventListener( Event.COMPLETE, complete_func );
uploadFile.addEventListener( DataEvent.UPLOAD_COMPLETE_DATA, show_message );
function browse( e:MouseEvent )
filefilters = [new FileFilter('Images',"*.jpg;*.png;*.gif")];
uploadFile.browse( filefilters );
function complete_func( e:Event )
trace( 'complete !' );
function show_message(e:DataEvent)
if (e.data == 'ok')
label_txt.text = 'The file has been uploaded.';
else if ( e.data == 'error')
label_txt.text = 'The file could not be uploaded.';
PHP Code:
<?php
$uploads_dir = './files/uploads';
if( $_FILES['Filedata']['error'] == 0 ){
if( move_uploaded_file( $_FILES['Filedata']['tmp_name'], $uploads_dir.$_FILES['Filedata']['name'] ) ){
echo 'ok';
exit();
echo 'error';
exit();
?>You need call another PHP file
<?php
$directory = './files/uploads';
getDirectoryList ($directory);
//This function find all the files in the directory
function getDirectoryList ($directory)
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($directory);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file != "." && $file != "..") {
//$results[] = $file;
// Delete Files
$filename = $file;
unlink($filename); //this delete a file
// tidy up: close the handler
closedir($handler);
?>
Maybe you are looking for
-
Sending email using UTL_SMTP
Dear experts, I am trying to send an email using UTL_SMTP (i switched from UTL_MAIL to UTL_SMTP since i need to send mails with large attachments - BLOB). I am using the demo_mail package given here: http://www.oracle.com/technology/sample_code/tech/
-
How to change Table Cell Field Type Dynamically?
Hi All, I am fetching some news data from backend DB and displaying them in a WD Table. Now one News Item may or may not have a URL behind it. If I find the URL as null then I want to display the news as simple TextView otherwise as LinkToUrl. How ca
-
How do i cose an open ntuser.dg file in adobe reader?
how do I close a ntuser.dg file that is open in adobe reader?
-
How to Save data from HR_INDVAL BADI
hI I M USING THE ABOVE BADI FOR CALCULATION OF BONOUS FOR INFOTYPE 15 .... IT IS CALCULATING VERY WEL BUT DATA IS NOT GETTING SAVE IN PA0015 . KINDLY HELP ME REGARDS AMMAD
-
Can I only combine several columns?
Dear expert, Have one quick question on BEX report, here is detail, Situation: Except build-in dimension, one infocube includes 1 additonal dimension, company code, the key figure are, sales amount, sales qty. The table content for this infocube are