utl_file и file list

HX
Дата: 17.09.2004 17:07:12
Как, сосбственно, получить список файлов в каталоге средствами одного Oracle?
Вадим
Дата: 17.09.2004 17:24:48
Встроенная java

CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED SYSLIB."l_jav" AS
import java.io.*;
import java.lang.*;
import java.sql.*;
import java.math.*;
import java.sql.Timestamp;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import oracle.oracore.*;
import oracle.jdbc2.*;
import oracle.*;
import java.util.*;



public class l_jav {
private static int SUCCESS = 1;
private static int FAILURE = 0;
private static int Poz = 1;

public l_jav() {}

public static void executeCommand(String command) {

try {
String[] finalCommand;
if (isWindows()) {
finalCommand = new String[4];
finalCommand[0] = "C:\\winnt\\system32\\cmd.exe";
finalCommand[1] = "/y";
finalCommand[2] = "/c";
finalCommand[3] = command;
}
else {
finalCommand = new String[3];
finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
}

final Process pr = Runtime.getRuntime().exec(finalCommand);
new Thread(new Runnable() {
public void run() {
try {
BufferedReader br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String buff = null;
while ((buff = br_in.readLine()) != null) {
buff = null;
//System.out.println("Process out :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
}
br_in.close();
}
catch (IOException ioe) {
//System.out.println("Exception caught printing process output.");
String buff = null;
ioe.printStackTrace();
}
}
}).start();

new Thread(new Runnable() {
public void run() {
try {
BufferedReader br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String buff = null;
while ((buff = br_err.readLine()) != null) {
//System.out.println("Process err :" + buff);
buff = null;
try {Thread.sleep(100); } catch(Exception e) {}
}
br_err.close();
}
catch (IOException ioe) {
String buff = null;
//System.out.println("Exception caught printing process error.");
ioe.printStackTrace();
}
}
}).start();
}
catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
}


public static boolean isWindows() {
if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
return true;
else
return false;
}


public static String getEmpName (String enum, String user, String passwd,
String host, String port, String sid)
throws SQLException
{
String name = null;
Connection conn = null;
Statement stmt = null;
try
{
// Connect to the database
// You must put a database name after the @ sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as <host>:<port>:<sid>. The example uses the short cut syntax.
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
String url = host + ":" + port + ":" + sid;
//Int RowNum = 1;
conn = DriverManager.getConnection ("jdbc:oracle:thin:@" + url, user, passwd);

// create a statement
stmt = conn.createStatement();

// find the name of the employee with the given employee number
ResultSet rset = stmt.executeQuery(enum);

// retrieve and print the results
while (rset.next())
{
name = rset.getString (Poz);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// don't forget to close the statement
if (stmt != null)
stmt.close();

if (conn != null)
conn.close();
// return the name of the employee who has the given employee number
return name;
}
}

public static String[] list (String path)
{
File myFile = new File (path);
return myFile.list();
}

public static String world ()
{
return "Hello world";
}

public static void Drop_Object (String object_type, String object_name)
throws SQLException {
// Connect to Oracle using JDBC driver
Connection conn = new OracleDriver().defaultConnection();
// Build SQL statement
String sql = "DROP " + object_type + " " + object_name;
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {System.err.println(e.getMessage());}
}


public static String dirContents (String dir, String listDelimiter) throws Exception
{
File myFile = new File (dir);
String[] filesList = myFile.list();
String contents = new String();
// for (int i = 0; i < filesList.length; i++) contents = contents + filesList + listDelimiter;
for (int i = 0; i < 21; i++) contents = contents + filesList + listDelimiter;

return contents;
}


public static void wageStrategy (STRUCT e) throws java.sql.SQLException
{
// Get the attributes of the labor_source object.
Object[] attribs = e.getAttributes();

// Access individual attributes by array index,
// starting with 0.
String laborType = (String)(attribs[0]);
BigDecimal hourly_rate = (BigDecimal)(attribs[1]);

// We'll simply display the two attribute values.
System.out.println (
"Pay " + laborType + " $" +
hourly_rate + " per hour");
}

public static void executeCommand (String command, String windows) throws IOException
{
String[] fullCommand = {"C:\\winnt\\system32\\cmd.exe", "/y", "/c", command};
if (windows.toUpperCase().equals("Y"))
Runtime.getRuntime().exec(fullCommand);
else
Runtime.getRuntime().exec(command);
}

public static int canRead (String path)
{
File myFile = new File (path);
if (myFile.canRead()) return SUCCESS; else return FAILURE;
}

public static int canWrite (String path)
{
File myFile = new File (path);
if (myFile.canWrite()) return SUCCESS; else return FAILURE;
}

public static int createNewFile (String path) throws IOException {
File myFile = new File (path);
if (myFile.createNewFile()) return SUCCESS; else return FAILURE;
}

public static int isHidden (String path)
{
File myFile = new File (path);
if (myFile.isHidden()) return SUCCESS; else return FAILURE;
}

public static Timestamp lastModified (String path)
{
File myFile = new File (path);
return new Timestamp(myFile.lastModified());
}

public static long length (String path)
{
File myFile = new File (path);
return myFile.length();
}


public static String readFileLine (String sFile, int line) {
try {
File file = new File(sFile);
if (file.isFile()) {
if (file.canRead()) {
String ret = new String();
FileReader freader = new FileReader(file);
LineNumberReader lnreader = new LineNumberReader(freader);

for (int i = 0; i <= line; i++) {
lnreader.setLineNumber(i);
ret = lnreader.readLine();
}
lnreader.close();
freader.close();
return ret;
}
else
return "ERROR:: File " + sFile + " is not readable";
}
else
return "ERROR:: File " + sFile + " does not exist or is not a normal file";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Read entire file as a string. NOTE: do not use this if file is greater than 4KB in size
*/
public static String readFileStr (String sFile) {
try {
File file = new File(sFile);
if (file.isFile()) {
if (file.canRead()) {
FileReader fr = new FileReader(file);
long fsize = file.length();
char[] cbuf = new char[(int) fsize];
int offset = 0;
int len = (int) fsize;
fr.read(cbuf, offset, len);
fr.close();
String ret = new String(cbuf);
return ret;
}
else
return "ERROR:: File " + sFile + " is not readable";
}
else
return "ERROR:: File " + sFile + " does not exist or is not a normal file";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Create an empty file
*/
public static String createEmptyFile (String sFile) {
try {
File file = new File(sFile);
if (file.createNewFile())
return "Done";
else
return "ERROR:: File " + sFile + " already exists";
}
catch (Exception e ) {
return "ERROR:: " + e.toString();
}
}
/*
* Write string to a file. If file already exists, string will be appended
*/
public static String writeFileStr (String sFile, String sStr) {
try {
File file = new File(sFile);
if (file.isFile()) {
if (file.canWrite())
return appendFileStr(sFile, sStr);
else
return "ERROR:: File " + sFile + " is not writeable";
}
FileWriter fw = new FileWriter (file);
fw.write(sStr + "\r\n");
fw.close();
return "Done";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Rename a file
*/
public static String renameFile (String sFileNameOld, String sFileNameNew) {
try {
File oldfile = new File(sFileNameOld);
if (oldfile.isFile()) {
File newfile = new File(sFileNameNew);
oldfile.renameTo(newfile);
}
else
return "ERROR:: File " + sFileNameOld + " does not exist or is not a normal file";
return "Done";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Delete a file
*/
public static String deleteFile (String sFile) {
try {
File file = new File(sFile);
if (file.isFile()) {
if (file.delete())
return "Done";
else
return "ERROR:: File " + sFile + " could not be deleted";
}
else
return "ERROR:: File " + sFile + " does not exist or is not a normal file";
}
catch (Exception e) {
return e.toString();
}
}
/*
* Check if file exists. Returns String "Yes" or "No"
*/
public static String isFileExist (String sFile) {
try {
File file = new File(sFile);
if (file.exists())
return "Yes";
else
return "No";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*************************
* DIRECTORY FUNCTIONS *

*************************
*
* Returns pipe delimited list of files in a directory sLocalDir given a file filter sFilter
* e.g. MyFile.txt|ThisFile.txt|...
*/
public static String getFileList(String sLocalDir, String sFilter) {
final String filter = sFilter;
class Filefilter implements FilenameFilter {
public boolean accept (File sdir, String name) {
if (name.endsWith (filter))
return true;
else
return false;
}
}
try {
String filelist = new String();
File dir = new File(sLocalDir);
String[] entries = dir.list (new Filefilter());
for (int i = 0; i < entries.length; i++) {
filelist = filelist + entries + "|";
}
if (filelist.length() == 0)
return null;
else
return filelist.substring(0, filelist.length() - 1);
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Create a new directory. All non existent parent directories will be created along the path.
* NOTE: If the function fails, some parent directories along the path may be created successfully.
*/
public static String createDir (String sDir) {
try {
File dir = new File(sDir);
if (dir.isFile())
return "ERROR:: " + sDir + " is a file";
if (dir.isDirectory())
return "ERROR:: Directory " + sDir + " already exists";
if (dir.mkdirs())
return "Done";
else
return "ERROR:: Directory " + sDir + " could not be created";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Remove a directory. NOTE: Removes a directory ONLY if it is empty
*/
public static String removeDir (String sDir) {
try {
File dir = new File(sDir);
if (dir.isFile())
return "ERROR:: " + sDir + " is a file";
if (dir.delete())
return "Done";
else
return "ERROR:: Directory " + sDir + " could not be removed because it is not empty";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/********************
* OS FUNCTIONS *
********************
*
* Return system dependant file separator. Unix = /, Win32 = \
*/
public static String getFileSeparator () {
try {
return File.separator;
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/****************************************************************
* STRING TOKENIZERS *
* Use these functions as helpers to tokenize a return string *
****************************************************************
*
* Tokenize a string and return desired token
*/
public static String strTokenize(String str, String delim, int indx) {
try {
/* Workaround for StringTokenizer not recognizing NULL token.
Insert a space for tokens e.g. || to be fixed as |" "| */
String fixstr = new String(str);
while (fixstr.indexOf(delim + delim) != -1) {
int i = fixstr.length();
int j = fixstr.indexOf(delim + delim) + 1;
fixstr = fixstr.substring(0, j) + " " + fixstr.substring(j, i);
}
StringTokenizer st = new StringTokenizer(fixstr, delim);
/* Using this instead of exception as this may be called in a loop.
Exit will be at NULL return */
if ((indx > st.countTokens()) || (indx <= 0)) {
return null;
}
Vector vt = new Vector();
while (st.hasMoreTokens()) {
String sVal = st.nextToken();
vt.addElement(new String(sVal));
}
/* Use indx - 1. First element in a vector is 0 */
return vt.elementAt(indx - 1).toString();
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/*
* Tokenize a string and return token count as String.
* Convert String to Number on PL/SQL side.
*/
public static String tokenCount(String str, String delim) {
try {
/* Workaround for StringTokenizer not recognizing NULL token.
Insert a space for tokens e.g. || to be fixed as |" "| */
String fixstr = new String(str);
while (fixstr.indexOf(delim + delim) != -1) {
int i = fixstr.length();
int j = fixstr.indexOf(delim + delim) + 1;
fixstr = fixstr.substring(0, j) + " " + fixstr.substring(j, i);
}
StringTokenizer st = new StringTokenizer(fixstr, delim);
String tc = new String();
tc = st.countTokens() +"";
return tc;
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}
/**********************
* PRIVATE FUNCTIONS *
**********************
*
* Append string to a file
*/
private static String appendFileStr (String sFile, String sStr) {
try {
FileWriter fw = new FileWriter (sFile, true);
fw.write(sStr + "\r\n");
fw.close();
return "Done";
}
catch (Exception e) {
return "ERROR:: " + e.toString();
}
}







public static String GetDirFiles(String maska, String razdel) throws Exception{
String result=null;
int iLen;

// Build SQL statement
String sql = null;

if(maska==null) maska="c:\\*.*"; //this.maska;
if(razdel==null) razdel="|"; //this.razdel;
String _dir = maska.substring(0,maska.lastIndexOf("/")+1);
String _maska = maska.substring(maska.lastIndexOf("/")+1).toLowerCase();
FileFilter filt = new MyFilter(_maska);
File _file = new File(_dir);
File[]mass= _file.listFiles(filt);
if(mass.length!=0){
StringBuffer sb = new StringBuffer(mass[0].getName());
iLen = mass.length;
if ( iLen>30) {iLen = 30;}

for(int i=1; i<iLen; i++)
{
sb.append(razdel);
sb.append(mass.getName());

}//for

result=sb.toString();
}//if
return result;
}


public static int exists (String path) {
File myFile = new File (path);
if (myFile.exists()) return SUCCESS; else return FAILURE;
}

public static int mkdir (String path) {
File myFile = new File (path);
if (myFile.mkdir()) return SUCCESS; else return FAILURE;
}

public static int mkdirs (String path) {
File myFile = new File (path);
if (myFile.mkdirs()) return SUCCESS; else return FAILURE;
}

public static int renameTo (String fromPath, String toPath) {
File myFromFile = new File (fromPath);
File myToFile = new File (toPath);
if (myFromFile.renameTo(myToFile)) return SUCCESS; else return FAILURE;
}


public static int delete (String path) {
File myFile = new File (path);
if (myFile.delete()) return SUCCESS; else return FAILURE;
}


}

class MyFilter implements FileFilter {
protected String mask=null;
public MyFilter(String mask) {
this.mask=mask.toLowerCase();
}
public boolean accept(File pathname) {
String filename, mask_start, mask_end, filename_start, filename_end;
if(pathname!=null){
if(pathname.isDirectory())return false;
mask_start = mask.substring(0,mask.lastIndexOf("."));
mask_end = mask.substring(mask.lastIndexOf(".")+1);
filename = pathname.getName().toLowerCase();
if(filename.lastIndexOf(".")<0){
filename_end="";
filename_start=filename;
}
else{
filename_start = filename.substring(0,filename.lastIndexOf("."));
filename_end = filename.substring(filename.lastIndexOf(".")+1);
}
if(check(filename_start,mask_start)&&check(filename_end,mask_end))return true;
}
return false;
}

private boolean check (String str, String sub){
if(sub.equals("*"))return true;
if (sub.startsWith("*")&&sub.endsWith("*")){
sub = sub.substring(1,sub.length()-1);
if(str.indexOf(sub)>0)return true;
}
if(sub.startsWith("*")){
sub=sub.substring(1);
if(str.endsWith(sub))return true;
}
if(sub.endsWith("*")){
sub=sub.substring(0,sub.length()-1);
if(str.startsWith(sub))return true;
}
if(sub.equals(str))return true;
return false;
}

}
/
HX
Дата: 18.09.2004 16:06:09
Спасибо большое. :-)