logo
down
shadow

How to Read Java File Structure using Java?


How to Read Java File Structure using Java?

By : Hugobuntux_Aldebian
Date : January 10 2021, 01:49 PM
will help you This can be accomplished using the Java Compiler API (introduced in Java 6). Unfortunately, this solution is limited to Sun's JDK. Therefore, you will have to have that JDK installed and you must include its tools.jar file in your class path.
code :


Share : facebook icon twitter icon
read file system structure from java

read file system structure from java


By : Mark
Date : March 29 2020, 07:55 AM
will help you Is it possible to read all the names of folders (not sub-folders) inside a directory and save the list in an ArrayList, etc ? , Try this:
code :
File dir = new File("directoryName");
File temp;
String[] children = dir.list();
if (children !=null) {
    for (int i=0; i<children.length; i++) {
        temp = new File(children[i]);
        if(temp.isDirectory()) //add children[i] to arrayList
    }
}
read folder structure from a text file and create the structure - java

read folder structure from a text file and create the structure - java


By : Ashwin Chandra
Date : March 29 2020, 07:55 AM
it fixes the issue I think this is quite a specific task, and so I don't know about any libraries that would do it for you out of the box. The main idea is that you want to keep note of the current ancestors of the processed line. You can do it with a stack. I wanted to find out if my algorithm actually works so I coded it up and it does work :) Hope it helps.
code :
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class DirStuctureReader {

  private static final int INDENTATION = 4;

  public static void main(String[] args) throws Exception {
    Directory result = new DirStuctureReader().read(new File("testfile.txt"));
    System.out.println(result);
  }

  public Directory read(File file) throws IOException {
    Scanner scanner = new Scanner(file);
    Stack<Directory> directoryStack = new Stack<>();
    Directory root = new Directory("/"); // a root directory for everything
    directoryStack.add(root);
    while (scanner.hasNextLine()) {
      processLine(scanner.nextLine(), directoryStack);
    }

    return root;
  }

  private void processLine(String line, Stack<Directory> directoryStack) {
    int nLeadingSpaces = getNumberOfLeadingSpaces(line);
    if (nLeadingSpaces == -1) return;
    int depth = nLeadingSpaces / INDENTATION;
    while (directoryStack.size() > depth + 1) {
      directoryStack.pop(); // discard elements from the stack when we are deep and jump up one or more levels
    }
    String dirName = line.substring(nLeadingSpaces + 1);
    Directory directory = new Directory(dirName);
    directoryStack.peek().getChildren().add(directory); // add the directory to the children of the proper parent dir
    directoryStack.push(directory);
  }

  private int getNumberOfLeadingSpaces(String line) {
    for (int i = 0; i < line.length(); i++) {
      if (line.charAt(i) != ' ') return i;
    }

    return -1;
  }

  public static class Directory {
    private List<Directory> children = new ArrayList<>();

    private final String name;

    public Directory(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }

    public List<Directory> getChildren() {
      return children;
    }
  }
}
How to read and write Java ArrayList Objects to and from a file that has a specific required structure

How to read and write Java ArrayList Objects to and from a file that has a specific required structure


By : David Wood
Date : March 29 2020, 07:55 AM
Any of those help In your example you use serialization (you can read more about it here Introduction to Java Serialization), which saves an object to a file in binary format. So basically you're saving the whole ArrayList, including its internal fields and values as an array of bytes.
But what you really need is simply writing to a text file.
code :
PrintWriter p = new PrintWriter("reservations.txt");
p.write("your text goes here");
Passenger p1 = new Passenger(0001, "John Smith", "1A", "AA12");
Passenger p2 = new Passenger(0002, "Annah Smith", "1B", "AA12");
p.write(p1.toString());
p.write(p2.toString());
How to read tree structure tab delimeted txt file in Java

How to read tree structure tab delimeted txt file in Java


By : Adrien Belleflamme
Date : March 29 2020, 07:55 AM
this will help This should work (warning: it could fail with unexpected input, i.e. a line with 2 tabs more than the previous):
code :
    Scanner keywords = new Scanner(new File("keywords.txt"));

    ArrayList<String> stack = new ArrayList<String>();
    ArrayList<String> csvLines = new ArrayList<String>();

    // stores the number of elements of the last line processed
    int lastSize = -1;

    while (keywords.hasNext()) {
        String line = keywords.nextLine();

        int tabs = 0;
        // Count tabs of current line
        while (line.length() > tabs // to avoid IndexOutOfBoundsException in charAt()
                && line.charAt(tabs) == '\t') {
            tabs++;
        }

        line = line.substring(tabs); // delete the starting tabs

        if (tabs <= lastSize) {
            // if the current line has the same number of elements than the previous line, 
            // then we can save the previous processed line as CSV 
            String csvLine = "";
            for (String element : stack) {
                if (csvLine.length() > 0) {
                    csvLine += ", ";
                }
                csvLine += element;
            }
            csvLines.add(csvLine);
        }

        // if the current line has less tabs than the previous, then cut the stack 
        for (int i = stack.size() - 1; i >= tabs; i--) {
            stack.remove(i);
        }

        // if the current line has more tabs than the previous, then add the new element to the stack
        if (tabs >= stack.size()) {
            stack.add(line);
        }

        // save the number of tabs of the current line
        lastSize = tabs;
    }
    keywords.close();

    // we have to save the last line processed
    if (lastSize >= 0) {
        // save line
        String csvLine = "";
        for (String element : stack) {
            if (csvLine.length() > 0) {
                csvLine += ", ";
            }
            csvLine += element;
        }
        csvLines.add(csvLine);
    }

    // print out CSV
    for (String string : csvLines) {
        System.out.println(string);
    }
Java - Read Hierarchical data from flat structure in text file and build hashmap

Java - Read Hierarchical data from flat structure in text file and build hashmap


By : Ali Rahnavard
Date : March 29 2020, 07:55 AM
should help you out The recursion is already pretty efficient. Here's what you can optimize:
Put recursion into a loop Use memoization in recursion/loop (avoid recomputing) Do not recompute ancestors every time getParent is called, precompute results and store them
Related Posts Related Posts :
  • how to use izpack to make my jar application to installer?
  • What is meant by src in Java Eclipse?
  • Create a mirrored linked list in Java
  • Examples of good JPA Java Desktop Application
  • Translate Java to Python -- signing strings with PEM certificate files
  • Algorithm Analysis tool for java
  • Java serial comm API - what does inputstream.read() return if a timeout occurs?
  • How do I make a background thread in Java that allows the main application to exit completely? This works in Linux, but
  • How to add an image dynamically at runtime in java
  • Java App on Mac asking for allow network connections everytime
  • Best actively maintained Java XMPP Library?
  • Multi-Threaded Application - Help with some pseudo code!
  • Scoping a StringBuilder inside a for loop
  • How to specify hash algorithm when updating LDAP via Java?
  • Class not found exception (org.apache.openjpa.enhance.PersistenceCapable) thrown in a client of WLS 10
  • In Java ,where in memory are class functions put?
  • How do I test expectedExceptionsMessageRegExp (exception message) using TestNG?
  • Help In understanding Multi Dimentional Arrays
  • No bean named '...' is defined and Spring @Resource annotation
  • Singleton design pattern vs Singleton beans in Spring container
  • flashvars object was not working in mozilla browser
  • Shell script to import mysql dump file
  • What are the best practices to separate data from users
  • May I use com.google.code prefix for my packages?
  • How to set classpath in manifest file , while creating JAR from eclipse?
  • dealing with voice in java
  • Error: java.security.AccessControlException: Access denied
  • How to verify the root trust of a ceritifcate
  • Searching for a standalone JSP compiler
  • Spring 2.5 managed servlets: howto?
  • iBatis get executed sql
  • GRAPH: find an algorithm to determine the shortest path from one point to another in a rectangular maze?
  • Efficient JSON encoding for data that may be binary, but is often text
  • Java-Hibernate-Newbie: How do I acces the values from this list?
  • Smallest executable for Windows
  • Java: matching two different type of array
  • how to accept valid e-mail id in text box?
  • How can I know where a Null Pointer Exception originated?
  • Memory limited image processing in server
  • Java Multiple ResourceBundles
  • How to serialize Java primitives using Jersey REST
  • Casting objects to Integer,string ,
  • Using Java how can I plot the path of a sprite in a straight line?
  • IntelliJ shortcut for inserting a null check?
  • Eclipselink and update trigger on multiple access to the database
  • How to ICMPs and traceroutes in Java
  • "NOT_SUPPORTED_BY_GUI" Exception in JCo
  • Controlling the order of PicoContainer startup
  • Transposing and Untransposing a String in java
  • Spring MVC- several parts/views from a controller
  • Critical tools that every Java Developer should have in his toolbelt?
  • How to get the compression ratio for a GZipped file?
  • Does TestNG has runner like SpringJUnit4ClassRunner
  • Understanding Java Wait and Notify methods
  • Sorting a text file by date - Date looks like DD/MM/YYYY
  • Subtracting days in a Calendar object
  • How to store and retrieve object of a swing component in database, java
  • Java invalid stream header Problem
  • How to send parameters with same encoding from javascript?
  • Authentication and authorization frameworks for java GUI applications
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk