English 中文(简体)
Java-Saving String Tokenizer编成阵列,以进一步处理其他方法
原标题:Java - Saving StringTokenizer into arrays for further processing in other methods

我先把Perl和Adhurm捆绑起来,而此时此刻,我被派到 Java。 因此,我不熟悉贾瓦的处理数据。

我的任务包括编制一份投入文件,其中我需要检查依赖情况,然后向有过境依赖者输出。 更明确的想法如下:

投入文件:

A: B C
B: C E
C: G
D: A

产出文件:

A: B C E G
B: C E G
C: G
D: A B C E G

So far this is what I ve got (separating the first and second token):

import java.util.StringTokenizer;
import java.io.*;

public class TestDependency {

    public static void main(String[] args) {

        try{

        FileInputStream fstream = new FileInputStream("input-file");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;

        while ((strLine = br.readLine()) != null)   {
            StringTokenizer items = new StringTokenizer(strLine, ":");

            System.out.println("I: " + items.nextToken().trim());

            StringTokenizer depn = new StringTokenizer(items.nextToken().trim(), " ");

                while(depn.hasMoreTokens()) {
                    System.out.println( "D: " + depn.nextToken().trim() );
            }
        }

        } catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
        }
    }
}

感谢任何帮助。 我可以想象,Perl或Adhur可以轻松地处理这一问题。 需要在 Java执行。

问题回答

这不是非常高效的记忆,需要良好的投入,但应当加以罚款。

public class NodeParser {

    // Map holding references to nodes
    private Map<String, List<String>> nodeReferenceMap;

    /**
     * Parse file and create key/node array pairs
     * @param inputFile
     * @return
     * @throws IOException
     */
    public Map<String, List<String>> parseNodes(String inputFile) throws IOException {

        // Reset list if reusing same object
        nodeReferenceMap = new HashMap<String, List<String>>();

        // Read file
        FileInputStream fstream = new FileInputStream(inputFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;

        // Parse nodes into reference mapping
        while((strLine = br.readLine()) != null) {
            // Split key from nodes
            String[] tokens = strLine.split(":");
            String key = tokens[0].trim();
            String[] nodes = tokens[1].trim().split(" ");
            // Set nodes as an array list for key
            nodeReferenceMap.put(key, Arrays.asList(nodes));
        }

        // Recursively build node mapping
        Map<String, Set<String>> parsedNodeMap = new HashMap<String, Set<String>>();
        for(Map.Entry<String, List<String>> entry : nodeReferenceMap.entrySet()) {
            String key = entry.getKey();
            List<String> nodes = entry.getValue();
            // Create initial node set
            Set<String> outSet = new HashSet<String>();
            parsedNodeMap.put(key, outSet);
            // Start recursive call
            addNode(outSet, nodes);
        }

        // Sort keys
        List<String> sortedKeys = new ArrayList<String>(parsedNodeMap.keySet());
        Collections.sort(sortedKeys);

        // Sort nodes
        Map<String, List<String>> sortedParsedNodeMap = new LinkedHashMap<String, List<String>>();
        for(String key : sortedKeys) {
            List<String> sortedNodes = new ArrayList<String>(parsedNodeMap.get(key));
            Collections.sort(sortedNodes);
            sortedParsedNodeMap.put(key, sortedNodes);
        }

        // Return sorted key/node mapping
        return sortedParsedNodeMap;
    }

    /**
     * Recursively add nodes by referencing the previously generated list mapping
     * @param outSet
     * @param nodes
     */
    private void addNode(Set<String> outSet, List<String> nodes) {
        // Add each node to the set mapping
        for(String node : nodes) {
            outSet.add(node);
            // Get referenced nodes
            List<String> nodeList = nodeReferenceMap.get(node);
            if(nodeList != null) {
                // Create array list from abstract list for remove support
                List<String> referencedNodes = new ArrayList<String>(nodeList);
                // Remove already searched nodes to prevent infinite recursion
                referencedNodes.removeAll(outSet);
                // Recursively search more node paths
                if(!referencedNodes.isEmpty()) {
                    addNode(outSet, referencedNodes);
                }
            }
        }
    }
}

然后,你可以从你的方案中提一下:

    public static void main(String[] args) {
        try {
            NodeParser nodeParser = new NodeParser();
            Map<String, List<String>> nodeSet = nodeParser.parseNodes("./res/input.txt");
            for(Map.Entry<String, List<String>> entry : nodeSet.entrySet()) {
                String key = entry.getKey();
                List<String> nodes = entry.getValue();
                System.out.println(key + ": " + nodes);
            }
        } catch (IOException e){
            System.err.println("Error: " + e.getMessage());
        }
    }

此外,产出没有分类,而是应当细微。

String s = "A: B C D";
String i = s.split(":")[0];
String dep[] = s.split(":")[1].trim().split(" ");
System.out.println("i = "+i+", dep = "+Arrays.toString(dep));




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签