【发布时间】:2014-09-05 05:13:48
【问题描述】:
这是一项正在进行的工作,但我想知道如何访问特定文件。 我的主要方法应该构造一个新的 FileInputStream ,并以一个新文件作为其参数。然后,我应该调用接受 FileInputStream 对象的 getCounts 方法来返回某种地图。在 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;
}
}
【问题讨论】:
-
为什么需要访问文件对象?输入流确实足以让您进行计数。
标签: java map character fileinputstream