Read files in directory
I'm trying to read in files with a specific name from a directory with this code:
String s=" ";
File dir = new File ("c:\test");
String myFiles [] = dir.list();
for(int i=0;i<myFiles.length;i++)
f(myFiles.substring(0,3).equals("test"))
BufferedReader br = new BufferedReader( new FileReader("c:/test" + "/" + myFiles ) );
s = br.readLine();
however I get null pointer exception error when I try to run it.
What am I doing wrong?
"\t" means a tab character. Escape the path properly:
This isn't a good way to do it. Have a look at the java.io.FileFilter interface. It's a more flexible, object-oriented way to do.
Why not encapsulate this into a method and pass in the directory path?
This works very nicely:
import java.io.*;
import java.util.*;
public class DirectoryContentsReader
public static final int DEFAULT_BUFFER_SIZE = 2048;
public static void main(String [] args)
try
if (args.length > 1)
Map contents = DirectoryContentsReader.read(new File(args[0]), new FilenameSubstringFilter(args[1]));
System.out.println(contents);
else
System.out.println("Usage: java DirectoryContentsReader <directory path> <filename substring>");
catch (Exception e)
e.printStackTrace();
public static Map read(File directory, FileFilter nameFilter) throws IOException
Map directoryContents = new TreeMap();
File [] files = directory.listFiles(nameFilter);
StringBuffer fileContents = null;
for (int i = 0; i < files.length; ++i)
if (files.isFile() && files[i].canRead())
fileContents = new StringBuffer(DEFAULT_BUFFER_SIZE);
BufferedReader br = new BufferedReader(new FileReader(files[i]));
String line = "";
String newline = System.getProperty("line.separator");
while ((line = br.readLine()) != null)
fileContents.append(line);
fileContents.append(newline);
br.close();
directoryContents.put(files[i].getCanonicalPath(), fileContents.toString());
return directoryContents;
class FilenameSubstringFilter implements FileFilter
private String substring = "";
public FilenameSubstringFilter(String substring)
this.substring = substring;
public boolean accept(File candidate)
return (candidate.getName().indexOf(substring) != -1);
Similar Messages
-
Read file from directory, update contents of the each file
hai,
I could not understand how to debug the error i have now.
target
1- read the files from directory // i able ot do this part
2- for each file
for each file read the content & compare with the existing List & update the list // i able to do this part
when i try to combine both parts , i got some following error
run:
E:\java\check\100130.ixf
Error: children[i] (The system cannot find the file specified)
BUILD SUCCESSFUL (total time: 2 seconds)
i can see from the code that children[i] only gives the error when i use that in the second part of the code.
can any one help me on this??
Thanks
Priyan
the original code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
public class CompareList
public static void main(String[] args){
ArrayList a1 = new ArrayList();
ArrayList a2 = new ArrayList();
a1.add("1");
a1.add("2");
a1.add("3");
a1.add("4");
a1.add("5");
a1.add("6");
a1.add("7");
a1.add("8");
a1.add("9");
a1.add("10");
a1.add("11");
a1.add("12");
a1.add("13");
a1.add("14");
a1.add("15");
a1.add("16");
a1.add("17");
a1.add("18");
a1.add("19");
a1.add("20");
a1.add("21");
a1.add("22");
a1.add("23");
a1.add("24");
a1.add("25");
a1.add("26");
a1.add("27");
a1.add("28");
a1.add("29");
a1.add("30");
a1.add("31");
a1.add("32");
a1.add("33");
a1.add("34");
a1.add("35");
a1.add("36");
a1.add("37");
a1.add("38");
a1.add("39");
a1.add("40");
a1.add("41");
a1.add("42");
a1.add("43");
a1.add("44");
a1.add("45");
a1.add("46");
a1.add("47");
a1.add("48");
a1.add("49");
a1.add("50");
a1.add("51");
a1.add("52");
try{
File dir = new File("E:\\java\\check");
File[] children = dir.listFiles();
if (children == null) {
System.out.println("does not exist or is not a directory");
else {
for (int i = 0; i < children.length; i++) {
System.out.println( children);
FileInputStream fstream = new FileInputStream("children[i]");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String line =strLine.substring(0,2);
// Print the content on the console
//System.out.println(line);
a2.add(line);
} // end of add list2
if (a1.size() > a2.size())
int k = 0;
for (int l = 0; l < a2.size(); l++)
if (!((String)a1.get(l)).equals((String)a2.get(l)))
//System.out.println((String)a2.get(i));
// System.out.println("dd");
k = l;
k++;
for (int l = k; l < a1.size(); l++)
System.out.println((String)a1.get(l));
String str = "children[l]";
File file = new File(str);
RandomAccessFile rand = new RandomAccessFile(file,"rw");
rand.seek(file.length()); //Seek to end of file
rand.writeBytes((String)a1.get(i)); //Write end of file
rand.writeBytes("., 0.");
rand.writeBytes("\n");
}// end of comparing and updating the list2
in.close();
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());thanks for the information.
i tried, the error
like this
run:
E:\java\check\100130.ixf
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1935)
at CompareList.main(CompareList.java:84)
BUILD SUCCESSFUL (total time: 0 seconds)this comes because in my code i used children[i] as string in the later part
else {
for (int i = 0; i < children.length; i++) {
System.out.println( children);
FileInputStream fstream = new FileInputStream(children[i]);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String line =strLine.substring(0,2);
a2.add(line);
System.out.println(line);
} // end of add list2
if (a1.size() > a2.size())
int k = 0;
for (int l = 0; l < a2.size(); l++)
if (!((String)a1.get(l)).equals((String)a2.get(l)))
//System.out.println((String)a2.get(i));
// System.out.println("dd");
k = l;
k++;
for (int l = k; l < a1.size(); l++)
System.out.println((String)a1.get(l));
String str = "children[l]";
File file = new File(str);
RandomAccessFile rand = new RandomAccessFile(file,"rw");
rand.seek(file.length()); //Seek to end of file
rand.writeBytes((String)a1.get(i)); //Write end of file
rand.writeBytes("., 0.");
rand.writeBytes("\n");
rand.close();
}// end of comparing and updating the list2
in.close();
i stil could not figure out it yet. do u have any clue with this. -
Reading files and directory from a directory
ublic static void readFromDirectory(String dirName) {
// stop word ArrayLists
ArabicStop();
EnglishStop();
FrenchStop();
SpanishStop();
DutchStop();
File dir = new File(dirName);
if (dir.isDirectory()) {
String[] child = dir.list();
System.out.println("hi Iam here");
for (int i = 0; i < child.length; i++) {
readFromDirectory(child.toString());
File[] files = dir.listFiles();
if (files == null) {
System.out.println("There are no files in this Directory ");
} else {
for (int j = 0; j < files.length; j++) {
String filename = files[j].toString();
readFile(filename);
if (dirName.equalsIgnoreCase("English")
|| dirName.equalsIgnoreCase("Nonenglish")) {
for (int i = 0; i < a2.size(); i++) {
keyWord = a2.get(i).toString();
//System.out.println("===" + keyWord + "===" + "KeyWord");
for (int a = 0; a < text.size(); a++) {
String t1 = text.get(a).toString();
if (keyWord.equalsIgnoreCase(t1)) {
count++;
//System.out.println("Found at:" + files[j] + " file");
keyWCount = count;
m1.put(keyWord, keyWCount);
//System.out.println(m1.get(keyWord));
count = 0;
} else if (dirName.equalsIgnoreCase("Spanish")) {
for (int i = 0; i < a5.size(); i++) {
keyWord = a5.get(i).toString();
//System.out.println("===" + keyWord + "===" + "KeyWord");
for (int a = 0; a < text.size(); a++) {
String t1 = text.get(a).toString();
if (keyWord.equalsIgnoreCase(t1)) {
count++;
//System.out.println("Found at:" + files[j] + " file");
keyWCount = count;
m1.put(keyWord, keyWCount);
//System.out.println(m1.get(keyWord));
count = 0;
//System.out.println(m1);
} else if (dirName.equalsIgnoreCase("French")) {
for (int i = 0; i < a3.size(); i++) {
keyWord = a3.get(i).toString();
//System.out.println("===" + keyWord + "===" + "KeyWord");
for (int a = 0; a < text.size(); a++) {
String t1 = text.get(a).toString();
if (keyWord.equalsIgnoreCase(t1)) {
count++;
//System.out.println("Found at:" + files[j] + " file");
keyWCount = count;
m1.put(keyWord, keyWCount);
//System.out.println(m1.get(keyWord));
count = 0;
public static void main(String[] args) {
int countText = 0;
int c;
test t1 = new test();
System.out.println("IN NON - ENGLISH DOCUMENTS - P :");
t1.readFromDirectory("NonEnglish");
for (int j = 0; j < text.size(); j++) {
if (!text.get(j).toString().equalsIgnoreCase("")) {
countText++;
c = countText;
//System.out.println(c);
//System.out.println(text.size());
for (int i = 0; i < a2.size(); i++) {
String word = a2.get(i).toString();
String m = (m1.get(word)).toString();
double x = Double.parseDouble(m);
System.out.println(word + ":" + (x / c) * 100 + " %");
I wanna read text files from directory that contain - lots of other directorys... and by using this code I have error,,,
Can anyone help me plzzz
Edited by: Shamma on Oct 9, 2008 3:32 AMYou actually have more than 1 problem: you cannot traverse directories recursively and you get a NullPointerException.
For the first problem you might want to verify what this statement returns:
child.toString() (I honestly don't understand why you are calling toString() on a String object, but that's not the real problem!)
You probably expect it to be a full absolute path.
The NullPointerException has already been pointed out by masijade. -
Hi all,
CALL 'C_DIR_READ_START' ID 'DIR' FIELD P_DIR
ID 'FILE' FIELD IT_FILEDIR-FILENAME
IF SY-SUBRC <> 0.
WRITE:/ 'Incorrect File'.
EXIT.
ENDIF.
This is my code for read particular file in server.
Iam passing p_dir and filename correctly .but this statement still failing .Can any one help me in this issue?Please see the following sample program for viewing the application server file system and reading the files into your ABAP 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 -
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 -
PI sender communication channel not reading files from NFS directory
Hello,
I have a sender communication channel configured to read file from NFS directory which is on ECC server. A program in ECC generates the file and puts it on the ECC server in the output directory. PI sender communication channel is supposed to pickup this file and process it. If I give the NFS path as the source directory, I am getting error: Configured source directory '//Server/DIR/OUT' does not exist. I tried putting '
Server\DIR\OUT' too but same error. Do I have to add the NFS path of ECC into PI as logical path?
Any suggestions?
Thanks,
SangitaHello Sangita,
Your ECC server is an external system, therefore you need to activate FTP service in that system and use the transport protocol FTP:
http://help.sap.com/saphelp_nw04/helpdata/en/e3/94007075cae04f930cc4c034e411e1/content.htm
You can use NFS protocol when you have a local directory in XI server.
Best Regards,
.Luis Bernal. -
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 -
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()); -
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() -
2 BPEL Processes doing Read at same directory in File Adapter.
Hi,
I am using File Adapter for Read operation. Normally we would make a Logical Directory for reading files at that location. There is a design design scenario where 2 BPEL processes will need to read file from same File location.
Incase such a design is implemented, will it work? And if yes, what will the precedence for reading file by BPEL processes. Also, will both of them read the files or one will be reading the file?
OR
Is there any other way that the same design can be implemeted??
I am using Oracle SOA 10.1.3.4 and JDeveloper 10.1.3.4.
Will really appreciate if someone can help in this regard.
Thanks for the needful.
Cheers,
VarunHi Varun
As per the best practice guide :
The file and FTP adapters support the high availability feature for the active-passive
topology. Perform the following steps to configure the adapter for this feature:
1. Create a shared folder on a highly available file system. This folder must have
write permissions and must be accessible from all systems running the file and
FTP adapters.
2. Open the pc.properties file available in the SOA_ORACLE_
HOME\bpel\system\service\config directory on each node.
3. Set oracle.tip.adapter.file.controldirpath to the shared folder name.
This is the shared folder that stores the control files for the adapter.
4. Restart the servers.
Note that in the case of Oracle ESB, you must rename SOA_ORACLE_
HOME\integration\esb\config\pc.
You can use a trigger file .tg to notify the second process that it can pick the file which the first process has written into the folder.
Regards
A -
Syn read file adapter throwing exception when file is not present directory
Hi Team,
Requirment is to check for a file is present in a soa directory .If present delete the existing and write a new one.
Syn read file adapter is throwing errors when file is not present in the directory soa local.
Any paramter we can add to skip this exception.
any help is appreciated.
Thanks all
Swetha H.Hi:
An alternative is that , before u try to read it, u make a list directory, and search for ur file, if it is not in the list, then u don't read; otherwise, u do.
The list operation is part of the file adapter.
hope this helps
best -
HOW TO READ MULTIPLE FILES FROM DIRECTORY
i have a directory with 100 .sql insert scripts.i want to read all .sql files from directory and execute the insert script automatically.
Let's suppose you have 3 files: "first.sql", "second.sql" and "third.sql". Create a file named "all.sql" in the same directory, containing this:
@@first.sql
@@second.sql
@@third.sqlRun "all.sql". -
Reading file from oracle directory at client side
Hi,
I have a SWING app. which connects to an Oracle db.
My goal is to read files from oracle directory with java through JDBC. I export some dumps with datapump and they need to be transferred to a client machine. There is no access to oracle directory at network filesystem level.
Please advice!
TIA, SandorAn Oracle Directory has an underlying OS directory associated with it, Oracle just overlays it's control structure onto an existing folder in the OS. You can manipulate the files with stored procedures in Oracle or at the OS level from outside of Oracle.
If you manipulate the files from the OS level, outside of Oracle, you may need a refresh of the Oracle Directory structure. -
Searching file from directory located at http path.
Hi All,
I have made the program to search for a file in a directory and its subdirectories. This is working fine when my directory is located on local machine. But if the same directory is placed in HTTP path, the code fails to search a directory. Does anyone has idea how can i connect to site so as to access the directories. I used URL and URLConnection to read and write file to the site, and this is also working fine but when it comes to directories i find no solution. Please help.This works fine if i map http://flash/ on my C: and
try to list files in directory C:\Mojo. Can you please
tell how can i know whether the http server i am
trying to access allows directory listing or not.
Because if it does not i have administrator rights on
the server and i can make the changes required.You can see if your Web server allows directory listing by simply
typing in the URL you want to examine, inside your browser, and see if
it shows you a directory listing. For instance, if you type in:
http://flash/Mojo/
in your browser's address bar, and you see a list of files in that
directory, then your Web server supports directory listing.
Note, though, that you can't use the File list() method to get a list of files.
You'll have to make a connection, read the input stream, and then parse
the filenames out of the HTML that the Web server returns. (You can see
what the HTML looks like, by doing View Source inside your brower. That's
what you'll get back from your Java program.)
--Steve -
Reading file from an external folder.
Iam tring to read an external file from the C:\ drive. Given below is the code.
DATA LV_XLS(100) TYPE C.
DATA LV_CONTENT TYPE XSTRING.
LV_XLS = 'C:\XML\Report.xls'
READ DATASET LV_XLS INTO LV_CONTENT.
But when i execute iam getting an error - FILE NOT FOUND. How do i read file from an external folder. My requirement is to strictly read from an external folder. Please help.
If this is not possible please advice as to how the file could be moved to the SAP root directory. Iam not able to locate the root.hi,
This is the code to read a excel file from the local system.
Read data set you are using in your code corresponds to files on application server thats the reason its throwing an error.
* Parameter variable declaration for browsing the file location *
PARAMETERS:
p_file TYPE ibipparms-path OBLIGATORY.
data:
it_text TYPE truxs_t_text_data .
AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
CALL FUNCTION 'F4_FILENAME'
EXPORTING
program_name = syst-cprog
* DYNPRO_NUMBER = SYST-DYNNR
field_name = ' '
IMPORTING
file_name = p_file.
START-OF-SELECTION.
CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
EXPORTING
* I_FIELD_SEPERATOR =
* I_LINE_HEADER =
i_tab_raw_data = it_text
i_filename = p_file
TABLES
i_tab_converted_data = t_cust
EXCEPTIONS
conversion_failed = 1
OTHERS = 2
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
This is to read a text file from local system.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
filename = 'D:\FILEINTERFACE\file.TXT'
* FILETYPE = 'ASC'
has_field_separator = 'X'
* HEADER_LENGTH = 0
* READ_BY_LINE = 'X'
* DAT_MODE = ' '
* CODEPAGE = ' '
* IGNORE_CERR = ABAP_TRUE
* REPLACEMENT = '#'
* IMPORTING
* FILELENGTH =
* HEADER =
TABLES
data_tab = t_kna1
* EXCEPTIONS
* FILE_OPEN_ERROR = 1
* FILE_READ_ERROR = 2
* NO_BATCH = 3
* GUI_REFUSE_FILETRANSFER = 4
* INVALID_TYPE = 5
* NO_AUTHORITY = 6
* UNKNOWN_ERROR = 7
* BAD_DATA_FORMAT = 8
* HEADER_NOT_ALLOWED = 9
* SEPARATOR_NOT_ALLOWED = 10
* HEADER_TOO_LONG = 11
* UNKNOWN_DP_ERROR = 12
* ACCESS_DENIED = 13
* DP_OUT_OF_MEMORY = 14
* DISK_FULL = 15
* DP_TIMEOUT = 16
* OTHERS = 17
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
PS. In both of the above mentioned function modules make sure that the file structure is similar to the internal tables used.
Thanks
Sharath
Maybe you are looking for
-
HP Laserjet 1536dnf MFP Installation Error
I have an HP Laserjet 1536dnf MFP printer which will not install. I originally had Windows 7 OS and got the HP 1536dnf printer which installed fine. However, I started getting the upgrade to Windows 8.1 pop-ups, which I avoided specifically. Howev
-
I just want to make sure I understand all this correctly. I am using Final Cut Express 1 and DVD Studio Pro 2, primarily on a Mac Mini using OS 10.3.9. The original QT Pro key supplied with DVD Studio was for 6.3 I believe. I must have inadvertantly
-
Curve/Level RGB Doesn't Change Individual Channels
Weird. When I adjust slider in Levels or point in Curves using the RGB master (default), and then go to the individual color channels, none of them have changed at all. Has anyone else seen this behavior?
-
Windows 8.1 skype no sound thru headpnones
after upgrading to windows 8.1, sound in my headphones when using skype calling is not working ( when making phone calls thru skype) I hear the voice in my laptop speakers but not in my headset. can you help, anyone with similar problem? my system is
-
Transparency problem for images
I have created a table for the main body of my site. In this main body table I would like to have images that stick out slightly over the sides of the table into the border areas on each side. These images I've made in photoshop all have pink as the