如何访问参数的参数?

时间:2014-07-15 06:06:27

标签: java map character fileinputstream

这是一项正在进行的工作,但我想知道如何访问特定文件。 我的主要方法是构造一个新的FileInputStream,并以新文件作为参数。然后,我应该调用getCounts方法接受FileInputStream对象来返回某种类型的map。在getCounts方法中,我无法完成此操作,因为我必须能够访问其中的文件,而FileInputStream似乎没有它的访问器。换句话说,如何在getCounts方法中访问用于构造作为参数进入getCounts方法的FileInputStream对象的文件?最终,我应该使用地图的键/值来获得文本文件中最重复的字符。感谢。

这是我的代码:

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


public class test2 {
public static void main(String[] q) throws FileNotFoundException {

    // This is for the character mapping
    Scanner console = new Scanner(System.in);
    System.out.println("Count characters of which file? ");
    FileInputStream output = new FileInputStream(new File(console.nextLine()));
    Map<Character, Integer> results = getCounts(output); 
    // do stuff with this map later on...
}

 // character counting method (WIP)
 public static Map<Character, Integer> getCounts(FileInputStream input) {
     Map<Character, Integer> output = new TreeMap<Character, Integer>(); // treemap keeps keys in sorted order (chars alphabetized)
     // Problem here: need to access the file object that was instiantiated
     byte[] fileContent = new byte[(int) file.length()]; // puts all the bytes from file into byte[] to process
     input.read(fileContent); 
     String test = new String(fileContent);

     // missing stuff here; use map to map keys as characters and occurrences as values.

     return output;
 }
}

2 个答案:

答案 0 :(得分:2)

如果您要使用FileInputStream,则需要循环,执行多次读取

byte[] fileContent = new byte [1024];

while ((input.read (fileContent) != -1) {

     // save fileContent somewhere
     // e.g.
     arrlist.add (new String (fileContent));

}

答案 1 :(得分:1)

理想情况下,我会将length作为参数传递给getCounts(),但由于您不允许这样做,您可以将文件长度保存为类静态参数:

private static long length;

public static void main(String[] q) throws IOException {

        // This is for the character mapping
        Scanner console = new Scanner(System.in);
        System.out.println("Count characters of which file? ");
        File file = new File(console.nextLine());
        FileInputStream output = new FileInputStream(file);
        length = file.length();
        Map<Character, Integer> results = getCounts(output);
        // do stuff with this map later on...
    }

    // character counting method (WIP)
    public static Map<Character, Integer> getCounts(FileInputStream input) throws IOException {
        Map<Character, Integer> output = new TreeMap<Character, Integer>(); // treemap keeps keys in sorted order (chars alphabetized)
        // Problem here: need to access the file object that was instantiated
        byte[] fileContent = new byte[(int) length]; // puts all the bytes from file into byte[] to process
        input.read(fileContent);
        String test = new String(fileContent);
        System.out.println("test = " + test);

        // missing stuff here; use map to map keys as characters and occurrences as values.

        return output;
    }