List all files, dirs and subdirs with tomahawk tree - recursion

I've been using tomahawk (1.1.11) for a project. I want to display a tree with all the files and subdirs (and files in those subdirs). I have a code, but it's not listing all of the files and dirs, and don't know where's the mistake.
public TreeNode getTreeData() {
path = loadConfiguredPath();
String dependencia = userVerifier.getDependencia();
if (dependencia.equals("TEST")) {
path = path + "dataFiles";
} else {
path = path + "dataFiles\\" + dependencia;
}
dirRoot = new File(path);
treeRoot = new TreeNodeBase("folder", "BASEDIR", false);
createTree(dirRoot, treeRoot);
return treeRoot;
}
private void createTree(File fileRoot, TreeNode treeRoot) {
File[] files = fileRoot.listFiles();
TreeNodeBase tnb;
for (File f : files) {
if (f.isDirectory()) {
tnb = new TreeNodeBase("folder", f.getName(), false);
treeRoot.getChildren().add(tnb);
createTree(f, tnb);
}
if (f.isFile()) {
tnb = new TreeNodeBase("file", f.getName(), false);
treeRoot.getChildren().add(tnb);
//return;
}
}
return;
}
UPDATE: code corrected as mention in comment.

Sorry, finally found my error !
I was returning when just one file was found. and I just change that return at the end of the for loop.
Thanks anyway

Related

Count Total Folder in asp.net

I need to read a folder that contains multiple inner folders, which have more than 100 xml files. I need to read all these xml files one by one. I am using asp.net c# . How can I achieve this.
For Example: A is my folder, containing 1,2,3,4,5,6...200 as sub-folders.
Now the folder 1 contains a.xml, b.xml, c.xml ... Similarly folder 2 contains 1.xml, 2.xml, 3.xml ...
Now I need to read all these xml files one by one from each folder.
you can make use of parallel linq and do as below
int count = 0;
string[] files = null;
try
{
files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("You do not have permission to access one or more folders in this directory tree.");
return;
}
catch (FileNotFoundException)
{
Console.WriteLine("The specified directory {0} was not found.", path);
}
var fileContents = from file in files.AsParallel()
let extension = Path.GetExtension(file)
where extension == ".xml"
let text = File.ReadAllText(file)
select new FileResult { Text = text , FileName = file }; //Or ReadAllBytes, ReadAllLines, etc.
try
{
foreach (var item in fileContents)
{
Console.WriteLine(Path.GetFileName(item.FileName) + ":" + item.Text.Length);
count++;
}
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException)
{
Console.WriteLine(ex.Message);
return true;
}
return false;
});
}
Example takem from : https://msdn.microsoft.com/en-us/library/ff462679%28v=vs.110%29.aspx

Issue faced reading an entry name from Tar InputStream

Facing problem regarding reading archive file recursively. I have created one recursive program which reads entry name from tar file or zip etc and will exit when some xyz extension found.
The code executes absolutely fine with proper entry name including archives having extension(eg, .zip,.tar,.tar.gz,.tgz), but it throws junk characters if the entry name is archive, but archive has no extension.
Eg: One archive inside another archive with no extension, viz, Ming_2nd.tar contains archive Ming_2nd which is an archive format
The following are the code and output.
public static String readTar4SrcType(TarInputStream tarInpStream) throws Exception{
TarEntry tarEntry = null;
int cnt = 0;
try {
tarEntry = tarInpStream.getNextEntry();
} catch (IOException e) {
src = "Other";
}
while (tarEntry != null) {
cnt++;
if (tarEntry.isDirectory()) {
System.out.println("Inside directory 4 Tar File..");
} else {
if (src.equals("tex") || src.equals("doc") || src.equals("docx")) {
break;
} else {
String entryName = tarEntry.getName();
System.out.println("entryName : " + entryName);
if(entryName.lastIndexOf("/")!=-1){
if (entryName.endsWith(".tar") || entryName.endsWith(".tar.gz") || entryName.endsWith(".tgz")){
readTar4SrcType(tarInpStream);
tarInpStream = null;
} else if (entryName.endsWith(".zip")) {
ZipInputStream zins = new ZipInputStream(tarInpStream);
readZIP4SrcType(zins);
zins = null;
} else if (entryName.endsWith(".tex")) {
System.out.println("TEX found...break");
src = "tex";
break;
} else if (entryName.endsWith(".doc") || entryName.endsWith(".docx")) {
System.out.println("DOC found...break");
src = "doc";
break;
} else {
src = "Other";
}
} else{
if(entryName.endsWith(".tex")){
src = "tex";
System.out.println("TEX found...break");
break;
} else if(entryName.endsWith(".doc") || entryName.endsWith(".docx")){
System.out.println("DOC found...break");
src = "doc";
break;
} else {
System.out.println("Invalid file format");
src = "Other";
}
}
}
}
tarEntry = tarInpStream.getNextEntry();
}
if(cnt==0) {
src = "Other";
}
return src;
}
??#????+^??NW}??C????????Y?c?>?uM??1??v?Q7????;Z8?DQ=?o??
Invalid file format
entryName : ?zv????????????3?^:??????|?>t?%oN???.5;??%z????_??kiqFt??l\?X??,m?????b
'?x(???????J5??j?x?%??
Invalid file format
entryName : +Dw???m?-?)????Ck??????4???>? ?e/???????^#????2?x$???z????????
entryName : ?~??Z
#5\?????&J7??{c?w{
Please provide me the solution as I am stuck for many days.

Vaadin 7: File Upload

I have a Upload component in which I´m supposed to import a xml file in order to parse it.
I´m trying to use the File.createTempFile method to create the file phisically,but something weird is going on.
For example,if I take the file named "test.xml" and use the createTempFile method to create it on the disk,the name of the generate file becomes something like 'test.xml13234xml'.How can I create the file the correct way?
This is expected when using i.e. createTempFile method as it implicitly creates a file with random prefix:
// a part of createTempFile method
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir) {
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
return new File(dir, prefix + Long.toString(n) + suffix);
}
which should give something like 'test.xml13234xml'.
If you want to create a file with the correct name and keep it for later use you can rename/move it within uploadSucceeded method.
public class ExampleUpload implements Upload.Receiver, Upload.SucceededListener {
private Upload xmlUpload;
private File tempFile;
public ExampleUpload() {
this.xmlUpload = new Upload("Upload:", this);
this.xmlUpload.addSucceededListener(this);
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
try {
tempFile = File.createTempFile(filename, "xml");
tempFile.deleteOnExit();
return new FileOutputStream(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
File destinationFile = new File("c:\\" + event.getFilename());
FileUtils.moveFile(tempFile, destinationFile));
// TODO read and parse destinationFile
} catch (IOException e) {
e.printStackTrace();
}
}
}

Downloading Multiple files from FTP Server using JSCH

I want to download all the files from FTP server using JSCH.
Below is the code snippet,
List<File> fileList = null;
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFolder);
for (ChannelSftp.LsEntry file : list) {
if( getLog().isDebugEnabled() ){
getLog().debug("Retrieved Files from the folder is"+file);
}
if (!(new File(file.getFilename())).isFile()) {
continue;
}
fileList.add(new File(remoteFolder,file.getFilename())) ;
return fileList;
The method will return List, for another method to download the files from the remote server using sftpChannel.get(src,dest) ;
Please let me know if the code is ok.
I don't have an environment to test, so can't confirm it.
But somewhat similar code i wrote for FTPClient and it works.
Appreciate your help.
You can use SftpATTRS to get the file information. You can declare a wrapper class to store file information. An example shown below.
private class SFTPFile
{
private SftpATTRS sftpAttributes;
public SFTPFile(LsEntry lsEntry)
{
this.sftpAttributes = lsEntry.getAttrs();
}
public boolean isFile()
{
return (!sftpAttributes.isDir() && !sftpAttributes.isLink());
}
}
Now you can use this class to test if the LsEntry is a file
private List<SFTPFile> getFiles(String path)
{
List<SFTPFile> files = null;
try
{
List<?> lsEntries = sftpChannel.ls(path);
if (lsEntries != null)
{
files = new ArrayList<SFTPFile>();
for (int i = 0; i < lsEntries.size(); i++)
{
Object next = lsEntries.get(i);
if (!(next instanceof LsEntry))
{
// throw exception
}
SFTPFile sftpFile = new SFTPFile((LsEntry) next);
if (sftpFile.isFile())
{
files.add(sftpFile);
}
}
}
}
catch (SftpException sftpException)
{
//
}
return files;
}
Now you can use sftpChannel.get(src,dest) ; to download files.

"File not found exception" trying to extract zip archive with DotNetZip

public void ZipExtract(string zipfilename, string outputDirectory)
{
using (ZipFile zip = ZipFile.Read(zipfilename))//file not found exception
{
Directory.CreateDirectory(outputDirectory);
zip.ExtractSelectedEntries("name=*.jpg,*.jpeg,*.png,*.gif,*.bmp", " ",
outputDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
[HttpPost]
public ContentResult Uploadify(HttpPostedFileBase filedata)
{
var path = Server.MapPath(#"~/Files");
var filePath = Path.Combine(path, filedata.FileName);
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}
filedata.SaveAs(filePath);
// CreateThumbnail(filePath);
_db.Photos.Add(new Photo
{
Filename = filedata.FileName
});
_db.SaveChanges();
return new ContentResult{Content = "1"};
}
I try to extract the uploaded zip archive and save extracted files in a folder but "file not found" exception happens all the time. What's the mistake?
Have you tried setting a break point here, and see what value filedata.FileName has? (And see if it actually exists on the server.)
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}

Resources