List contents of Directory using File Object.
Hi. I am new to Java.
Right now I want to list the contents of a specific directory. One approach is to use FILE array. But I just cannot get it right. Am i missing out something?
Thanks.
My idea was to retrieve the contents of directory and then when the form loads; the contents of directory (only directorys, not files; hence i think i can use isDirectory to check) will be loaded into a listbox (DefaultListModal i supposed)
I ran it without any errors. The Listbox is loaded; but then the listbox reads
Java.lang.String;@1a7508a
What went wrong?
Similar Messages
-
Question about using file objects
Hi,
I have two somewhat related issues in using file objects.
In one app, a simple swing gui that passes a file to a sax parsing class and reports back any errors, if I parse a file using the app, then try to edit the file I'm parsing (in another application) and save, I get an error message. I need to close the parsing app before I can save the file.
In another app I wrote, one that takes a group of files and runs an xslt stylesheet on them, if I select too many files, I get an OutOfMemory error, which leads me to believe that as the files go through multilple processes, they stay alive on the heap.
a file object is basically just a pathname, right? If I'm not using a BufferedWriter, or InputStreamReader or whatever, you can't really close a file...will the notifiy() method let the jvm know that it can let go of the file?
thanks,
bpA File object is just a path, it doesn't open the file or lock it, etc.. But if you are parsing the file, you must be opening (and forgetting to close it).
-
How to get the current directory as File object
Hi guys,
i want to get the current working directory as a file object.
plz help me on that if there are any standard methods present for this.new File(".");
-
Using File Object in JavaFX 2.2 to set home directory
Am I going bongers or what? Or is there a bug? Has anyone had this problem with the following line:
File dir = new File(getClass().getResource(".").getFile()); <-- this line is the culprit
Choose.setInitialDirectory(dir);
causing your programme to crash and generate the following error:
java.lang.NullPointerException under JavaFX 2.2?
I know it worked perfectly fine under JavaFX 2.1. So what's changed?My guess.
With JavaFX 2.1 you were using NetBeans 7.1
With JavaFX 2.2 you are using NetBeans 7.2
Under NetBeans 7.1 the default for JavaFX projects was to run the compiled classes from the file system.
Under NetBeans 7.2 the project can no longer be run from the file system, only from a jar which NetBeans builds using the JavaFX packaging tasks.
When you run a java program from classes off the file system the getResource call will use the file: protocol. Under this protocol directory specifiers like . and .. are valid.
When you run a java program from a jar the getResource call will use the jar: protocol. Under this protocol directory specifiers like . and .. are invalid.
So your upgrade of your NetBeans version just exposed an existing bug in your program which you were unaware of.
If you packaged the same program as a jar and tried to run the jar with a JavaFX 2.1 runtime environment you would have got the same error. -
Cannot create list in SharePoint 2010 using Client Object Model
I am trying to utilize SharePoint 2010 Client Object Model to create a List based on a custom template. Here's my code:
public void MakeList(string title, string listTemplateGUID, int localeIdentifier)
string message;
string listUrl;
List newList;
Guid template;
ListCreationInformation listInfo;
Microsoft.SharePoint.Client.ListCollection lists;
try
listUrl = title.Replace(spaceChar, string.Empty);
template = GetListTemplate((uint)localeIdentifier, listTemplateGUID);
listInfo = new ListCreationInformation();
listInfo.Url = listUrl;
listInfo.Title = title;
listInfo.Description = string.Empty;
listInfo.TemplateFeatureId = template;
listInfo.QuickLaunchOption = QuickLaunchOptions.On;
clientContext.Load(site);
clientContext.ExecuteQuery();
lists = site.Lists;
clientContext.Load(lists);
clientContext.ExecuteQuery();
newList = lists.Add(listInfo);
clientContext.ExecuteQuery();
catch (ServerException ex)
Now, this particular part, newList = lists.Add(listInfo); clientContext.ExecuteQuery();, the one that is supposed to create the actual list, throws an exception:
Message: Cannot complete this action. Please try again.
ServerErrorCode: 2130239231
ServerErrorTypeName: Microsoft.SharePoint.SPException
Could anyone please help me realize what am I doing wrong? Thanks.I've made progress - well, at least to some extent. The previous message related to the "Invalid file name" is not appearing any more. I now realize that it is necessary to specify feature ID, list template kind, as well as custom schema in order
to order SharePoint 2010 to create the document library.
However, there's a new problem which isn't documented on the net almost at all (at least I was unable to find anything): The document library gets created, but I cannot access it. Further inspection showed that the doc lib views are not created. Basically,
the only accessible doc lib page is the document library settings page. Also, I get the server exception with the message:
Server Out Of Memory. There is no memory on the server to run your program. Please contact your administrator with this problem.
Any idea what is causing this issue? Thanks.
Hi Boris
Borenović,
I think I found the reason for this notorious "Server Out Of Memory" error.
(Man, it took 4 hrs of frustrating troubleshooting without any direct hints... very disappointing
MSFT developers :( ).
Anyway,
All the "Form" elements at the bottom need to have SetupPath="pages\form.aspx"
attribute (by default this attrib is missing when you copy the whole List element from inside the stp's manifest.xml file).
Also, just make sure that each "View" element has correct "WebPartZoneID", "SetupPath" and "Url" attribute values otherwise that list/library will
be created successfully but will fail to load when you try to access it (with the VERY helpful "Cannot complete this action, contact administrator" error). Even if you enable stack trace (or check ULS logs) you will find "An unexpected
error has been encountered in this Web Part. Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe." and you will never realize it's because of the
incorrect attributes ("WebPartZoneID", "SetupPath" or "Url" as mentioned above).
Come on Microsoft, you can do better than that?
If the API needs this attrib then why is it missing inside the manifest.xml file when
an STP file generated in the first place? -
Writing to 2 different directory using file receiver channel
I have a scenario where i am picking multiple files from one server and writing it on another. While writing the files, i want to write them to different folders using one communication channels based on the filename. is it possible? if yes how?
You have to go for dynamic configuration UDF in the mapping.
Refer to the below document
http://wiki.scn.sap.com/wiki/display/XI/Dynamic+file+name+and+directory+in+Receiver+File+Adapter+-+summary+of+possibilities
Also http://****************/Tips/XI/ASMA/Index.htm
You just need to add filters/fix value lookup and pass it to UDF to determine the target directory
Message was edited by: Hareesh Gampa -
SharePoint list to sql table using client object model
here is my code
static void Main(string[] args)
ClientContext context = new ClientContext("http://sp2010");
Web web = context.Web;
List list = context.Web.Lists.GetByTitle("Emp");
context.Load(list);
context.ExecuteQuery();
Console.WriteLine(list.Title + "\n");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection allitems = list.GetItems(query);
context.Load(allitems);
context.ExecuteQuery();
foreach (ListItem listitem in allitems)
Console.WriteLine(listitem["desc"].ToString());
string connString = "connection string";
string a = "insert into emp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(a, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
// da.Fill(dataTable);
conn.Close();
da.Dispose();
DataTable table = new DataTable();
table.Columns.Add("desc");
DataRow row = table.NewRow();
table.Rows.Add(row);
//Console.WriteLine("row added");
da.Fill(table);
Console.Read();Excel + PowerPivot.
Scott Brickey
MCTS, MCPD, MCITP
www.sbrickey.com
Strategic Data Systems - for all your SharePoint needs -
Hi,
Does anyone know how to create List of most recent used files and display it in the main menu?
Has anyone done that?
Currently, I am opening one file at the time and I have the last
path of opened file.
thanx !You could recurse over the file system, creating a bunch of File objects, which you'd stick into a List. Then create a comparator that sorts the objects by File.lastModified() value, descending.
Then you'd have a sorted list, from which you could easily take the N most recent files.
Of course, the recursing would take a while. You may want to put creation and/or updating of this list, into a low priority thread. -
Most Recent Used File List in Menus
Hi,
Does anyone know how to create List of most recent used files and display it in the main menu?
Has anyone done that?
Currently, I am opening one file at the time and I have the last
path of opened file.
thanx !Offhand, you'll have to do it the hard way. I don't think Swing or Awt provide a default JMenuItem(), MenuItem() that does the file list. Now that you mention it, it does seem like an interesting project to do.
You essentially need an array of the files, and for each file, create the associated menu entry, as in:
String entryName = files[ i ];
if ( entryName.length > 10 ) {
entryName = entryName.subString( 0, 10 );
JMenuItem entry = new JMenuItem( i + ". " + entryName );
...and define the event listeners however appropriate for your application. -
Hi!
Is their some kind of way one can use File objects in a jar file plz? I have a project which is complete and working well on the IDE but now that I have jarred it, i've come to realize that apparently file objects do not relate well with .jar files. The problem is that the program makes a lot of file manipulations and changing everything to getResource, InputStream etc would be very lengthy. So there's absolutely no way in which one can use File objects in jar files?
Any help would be very much appreciated!
Thanks and regards,
Krt_MaltaYou can use the java.net.JarURLConnection class (use file:/// when creating the URL) to get a URL to a jar entry, create a URI from the URL, and then create a File object on the URI.
Or use java.util.jar.JarFile methods and its associated classes to get jar entry contents.
While you can use these approaches to create File objects from a jar, they are not any easier than what's already been mentioned.
And all you can do is read or delete a jar - jar entries can't be rewritten. -
How to get the read input file name in bpel process using File Adapter.
Hi,
I am reading a .txt file from configured directory using File Adapter.
I had configured file adapter to read file with naming pattern “SalesOrder.*\.txt”.
Now I had requirement to access the actual file name in bpel process eg: “SalesOrder123.txt”
How can I get the file name in bpel process.
Any help is appreciated.
Vidya.1) create a variable of message type. Click on Browse Message type. Here you select Message Type-->Project WSDL Files -->fileAdapterInboundHeader-->Message Types-->Inboundheader_msg. Then click OK
2)Next dbl Click on teh receive Activity which is receing your File from teh File Adapter. Go to the Adapter Tab. Click on Browse variable and select the variable that you had just created above.
This would get the File name in the variable declared -
List file under directory using JSP
Hi,
Does anyone have a code to list all files under a certain directory in JSP? Thanks alot!thank you so much... l already have a code working, but l can't make it download excle file as it displays them online. l want to force download. thanks
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page errorPage="listFiles_error.jsp" %>
<%
// To change the directory that is listed, change this variable
// \ character must be escaped with a second \ as below
String directoryName = "c:\\Tomcat\\webapps\\examples\\jsp";
// This variable needs to point to the URL that will be after the
// domain name for the above directory (needs to be setup in your
// application server)
String urlName = "/examples/jsp/";
// Loads the list of files in the directory
File directory = new File(directoryName);
File[] fileList = directory.listFiles();
Hashtable sortedFiles = new Hashtable(fileList.length);
// Loops through each file
for(int i=0; i<fileList.length; i++) {
File file = fileList;
// Skip subdirectories
if(file.isDirectory())
continue;
String name = file.getName();
int dotIndex = name.indexOf('.');
// Skip files with no extension
if(dotIndex < 0 || dotIndex+1 >= name.length())
continue;
String fileName = name.substring(0,dotIndex);
String fileType = name.substring(dotIndex+1).toLowerCase();
// Only process PDF, REP, and XLS file types
if(!fileType.equals("pdf") && !fileType.equals("rep") && !fileType.equals("xls"))
continue;
// Organize like filenames for processing later
Hashtable fileTypes = (Hashtable)sortedFiles.get(fileName);
if(fileTypes == null) {
fileTypes = new Hashtable(10);
sortedFiles.put(fileName,fileTypes);
fileTypes.put(fileType,file);
%>
<html>
<head>
<title>
listFiles
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body {
background-image: url(bkg2.gif);
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
.style2 {font-size: large; color: #000066; }
.style3 {font-size: medium; color: #000066; }
-->
</style></head>
<body bgcolor="#ffffff">
<table width="100%" border="0">
<tr>
<th background="chead.gif" scope="col"><div align="left"><img src="jpmorgan_logo.gif" width="200" height="40" border="0"></div></th>
</tr>
</table>
<p> </p>
<TABLE width="700" height="106" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#000033">
<tr>
<th width="370" height="33"><div align="left" class="style2">Name</div></th>
<th width="40"><div align="left" class="style2">PDF</div></th>
<th width="40"><div align="left" class="style2">Rep</div></th>
<th width="40"><div align="left" class="style2">Excel</div></th>
</tr>
<%
// Loop through each file name, outputting the data in a tabular format.
Enumeration e = sortedFiles.keys();
while(e.hasMoreElements()) {
String fileName = (String)e.nextElement();
Hashtable fileTypes = (Hashtable)sortedFiles.get(fileName);
File pdfFile = (File)fileTypes.get("pdf");
File reportFile = (File)fileTypes.get("rep");
File excelFile = (File)fileTypes.get("xls");
%>
<tr>
<td height="63" align="left" valign="bottom"><div align="left" class="style3"><%=fileName%></DIV></td>
<% if(pdfFile != null) {
// Output the PDF Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+pdfFile.getName()%>"><img src="PDF.gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="40" align="left" valign="bottom"> </td>
<% }
%>
<% if(reportFile != null) {
// Output the Report Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+reportFile.getName()%>"><img src="Rep.gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="1" align="left" valign="bottom"> </td>
<% }
%>
<% if(excelFile != null) {
// Output the Excel Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+excelFile.getName()%>"><img src="xls.Gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="1"> </td>
<% }
%>
</tr>
<%
%>
</table>
</body>
</html> -
I have downloaded a file from a FTP site into a File object. This file doesn't actually exist the file itself is in memory. Instead of using the renameTo() command to save the file to the hard drive I want to take the file and get its contents and store it in a string object? Im imaging this is something like a FileStream object but im not sure. Here is a snippet that I shows I have successfully downloaded the file off the FTP site and I want to get its contents ands tore it in a string besides saving to a file. Below I am saving the file to a hard drive but I do not want to do this anymore.
String currString = (String)fileListNames.get(c);
currentFile = ftps.download(currString);
File dummy = new File(config.getConfig("billEDIDir") + currString);
fileList[c] = config.getConfig("billEDIDir") + currString;
if(dummy.exists())
dummy.delete();
currentFile.renameTo(dummy);
Thanks for any help!Im creating a Java Service in the webMethods Intergration Tool. Here is the entire class.
****************************CODE************************************
IDataCursor pipelineCursor = pipeline.getCursor();
int count,currCount;
String error = "";
String status = "";
Ftps ftps = null;
File currentFile = null;
Enumeration x;
Enumeration y;
ArrayList fileListNames = new ArrayList();
try
ftps = new Ftps("*******","********","*********");
ftps.setDataPortRange(6100,6199);
ftps.setPassive(true);
ftps.connect();
ftps.setBinary();
ftps.setDir("outbound");
ftps.setDir("KUED");
count = 0;
for (x = ftps.getNameListing(); x.hasMoreElements() ;)
count++;
x.nextElement();
currCount = 0;
for (y = ftps.getNameListing(); y.hasMoreElements() ;)
currCount++;
String m = (String)y.nextElement();
fileListNames.add(currCount - 1,m.toString());
status = ftps.getDirListingAsString();
catch(FtpException fexp)
error = fexp.getMessage();
throw new ServiceException( fexp.toString() );
catch(Exception e)
error = e.getMessage();
throw new ServiceException( e.toString() );
String [] fileList = new String[count];
String [] fileContentList = new String[count];
try
for(int c=0;c<fileListNames.size();c++)
String currString = (String)fileListNames.get(c);
currentFile = ftps.download(currString);
File dummy = new File(config.getConfig("billEDIDir") + currString);
fileList[c] = config.getConfig("billEDIDir") + currString;
if(dummy.exists())
dummy.delete();
currentFile.renameTo(dummy);
//In this string list store the contents of each file downloaded.
fileContentList[c] = "";
ftps.disconnect();
catch(Exception e)
error = e.getMessage();
throw new ServiceException( e.toString() );
IDataUtil.put( pipelineCursor, "status", status );
IDataUtil.put( pipelineCursor, "error", error );
IDataUtil.put( pipelineCursor, "fileList", fileList );
IDataUtil.put( pipelineCursor, "fileContentList", fileContentList );
pipelineCursor.destroy();
****************************CODE************************************ -
Get_file_list to list content of UNIX directory
Hi all
I am trying to list the files in a UNIX directory using the get_file_list action. Not getting anything back, but action is not reporting error.
In the folder configuration box i have used all combinations of \ and / but none do anything. I can list files on our Mii server using
server\share but this is a windows machine.
I think i have a couple of options
1. get FTP set up on UNIX server and use the FTP_get_file_list action and move files to Mii server for processing.
2. get something like SAMBA set up on UNIX to allow windows style file sharing.
Any other ideas out there?Hi Les,
Set the "Get_File_List_0" with the following parameters:
Folder: "web://PROJECT"
Mask: "*" for list all files
http://wbhelp.sap.com/manufacturing/xmii_120/en/44/7108DF9EA03ABEE10000000A155369/content.htm (for more details)
Or use a XMLQuery
server://XMII/Catalog?Mode=ListFolders&Folder=[Param.1]&Content-type=text/xml
[Param.1] = PROJECT
Hope this help.
Danilo Santos -
Using File.list()
Hi,
Im using FMS 3 on the server side when onConnect occures i
need an array of all file that is the directory root/streams/myApp
how do use the File.list() ? do i need to create a new file
just for getting the list of files of the directory? and how do i
get to do that on the directory i want ? is it like this:
File.list(function(name){ return
name.indexOf("streams/myApp/")!=-1);
i so the example in the doc files :
var a = x.currentDir.list(function(name){return
name.length==3;});
does x is a File object? and where the currentDir came from
its not a File property?
Please help ...In SSAS, File objects represent both files and directories.
The "x" in the examples just means "arbitrary thing that has
a member of whatever type we're talking about." In this case, "x"
is something that has a member called "currentDir" that's a File
object (presumably representing the current directory).
I'm pretty sure you can create an equivalent like this:
currentDir = File(".");
Also, your search isn't going to work the way you expected.
The find function doesn't search all subfolders recursively, and
the name parameter only gets the filename (the last component of
the path), not the entire pathname. You're going to want to open
streams/myApp as a File, then just list everything in it.
Maybe you are looking for
-
The headphone jack on my new Verizon iPhone doesn't work. What can I do?
I bought an iPhone 4 from Verizon's website two weeks ago. This morning I plugged in the headphones for the first time and there appears to be a short or bad contacts or something. Sometimes partial audio will come through (distant and mono) and ot
-
TS4079 how to get fast cellular data on ipad 2
hai, i need to improve internet speed on pad 2.. please help it...
-
Commercial Price3 in Accounting View
Hello Experts, currently we are not using any commercial price fields in the material master Accounting view. Our user wants to use the commercial price3 field for some other purpose. None of our costing variants uses this field for cost updates. Wha
-
How to encrypt the backup that is taken by DPM
Hi all, Our client is using DPM to backup his data, we need to provide him with a step by step guide on how to encrypt this backup by DPM, any help?
-
Greetings, I cannot get audio to or from LE. Here is the configuration. Dedicated synth analogue out to MOTU 828 analogue in, Core audio enabled, Driver: MOTU 828mk2 Midi Inst. track records midi data correctly. When I playback the midi track and "Ar