Как получить доступ к параметру параметра?

это незавершенная работа, но мне было интересно, как получить доступ к определенному файлу. Мой основной метод должен создать новый FileInputStream с новым файлом в качестве параметра. Затем я должен вызвать метод getCounts, который принимает объект FileInputStream, чтобы вернуть какую-то карту. Внутри метода getCounts у меня возникли проблемы с завершением этого, так как я должен иметь доступ к файлу внутри него, и FileInputStream, похоже, не имеет для него доступа. Другими словами, как мне получить доступ к этому файлу, используемому для создания объекта FileInputStream, который входит в метод getCounts в качестве параметра внутри метода getCounts? В конечном счете, я должен использовать ключи/значения карты, чтобы получить наиболее повторяющийся символ текстового файла. Спасибо.

Вот мой код:

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;
 }
}

person Jack L.    schedule 15.07.2014    source источник
comment
Зачем вам нужен доступ к файловому объекту? Входной поток дает вам достаточно для подсчета.   -  person BetaRide    schedule 15.07.2014


Ответы (2)


В идеале я бы передал 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;
    }
person Nir Alfasi    schedule 15.07.2014
comment
По какой-то причине назначение требует, чтобы getCounts принимал FileInputStream и возвращал карту. - person Jack L.; 15.07.2014
comment
Я считаю, что он просто хочет объект file, чтобы он мог сделать file.length - person Scary Wombat; 15.07.2014
comment
Хорошо спасибо. Поскольку мне разрешено использовать только FileInputStream в качестве параметра, мне придется вручную определить размер массива, как предложил Scary Wombat. - person Jack L.; 15.07.2014
comment
@ScaryWombat 3 причины: 1) это работает. 2) это хорошее решение. 3) минимальные изменения кода. - person Nir Alfasi; 15.07.2014
comment
Поскольку он читает целые большие романы, я не уверен, что чтение такого большого количества данных в одном фрагменте является хорошим решением или даже возможным. - person Scary Wombat; 15.07.2014
comment
@ScaryWombat хорошо, в таком случае ты прав. +1 от меня ;) - person Nir Alfasi; 15.07.2014

Если вы собираетесь использовать FileInputStream, вам нужно будет выполнить цикл, выполняя несколько чтений

byte[] fileContent = new byte [1024];

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

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

}
person Scary Wombat    schedule 15.07.2014
comment
Это может показаться глупым вопросом, но почему 1024 элемента для byte[] fileContent? - person Jack L.; 15.07.2014
comment
это произвольное число, может быть 2048, 1234 или 6734, но входной поток будет считывать только этот объем данных перед возвратом. - person Scary Wombat; 15.07.2014
comment
Я планирую использовать это для чтения персонажей больших романов, поэтому у меня должно быть что-то вроде: byte[] filecontent = new byte[Integer.MAX_VALUE]; просто для безопасности? - person Jack L.; 15.07.2014
comment
см. stackoverflow.com/questions/8748960/ - person Scary Wombat; 15.07.2014