1
큰 파일은 1250 선은 단지 하나의 폴란드어 단어를 잇달아입니다 인코딩 내가 한 아주 빠른 방법. 나는 이것을했으나이 단어들을 인쇄 할 때 그들은 잘못된 인코딩을 가지고있다. [zaj? c, dzie? o, kiepsko ...], 나는 UTF8이 필요하다. 그래서 코드를 파일을 읽는 줄뿐만 아니라 줄을 읽도록 변경하여 내 노력이 다음 코드로 끝났습니다.읽기 문자열
public List<String> getRandomWordsFromDictionary(int number) {
List<String> randomWords = new ArrayList<String>();
File file = new File("file.txt");
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
for(int i = 0; i < number; i++) {
Random random = new Random();
int startPosition;
String word;
do {
startPosition = random.nextInt((int)raf.length());
raf.seek(startPosition);
raf.readLine();
word = grabWordFromDictionary(raf);
} while(checkProbability(word));
System.out.println("Word: " + word);
randomWords.add(word);
}
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
}
return randomWords;
}
private String grabWordFromDictionary(RandomAccessFile raf) throws IOException {
byte[] wordInBytes = new byte[15];
int counter = 0;
byte wordByte;
char wordChar;
String convertedWord;
boolean stop = true;
do {
wordByte = raf.readByte();
wordChar = (char)wordByte;
if(wordChar == '\n' || wordChar == '\r' || wordChar == -1) {
stop = false;
} else {
wordInBytes[counter] = wordByte;
counter++;
}
} while(stop);
if(wordInBytes.length > 0) {
convertedWord = new String(wordInBytes, "UTF8");
return convertedWord;
} else {
return null;
}
}
private boolean checkProbability(String word) {
if(word.length() > MAX_LENGTH_LINE) {
return true;
} else {
double randomDouble = new Random().nextDouble();
double probability = (double) MIN_LENGTH_LINE/word.length();
return probability <= randomDouble;
}
}
하지만 뭔가 잘못되었습니다. 이 코드를보고 도와 주시겠습니까? 어쩌면 몇 가지 명백한 오류를 볼 수는 있지만 분명하지 않습니다. 나는 어떤 도움을 주셔서 감사합니다.
하지만이 단어가 UTF8로 필요합니다. UTF8로 변환 할 수있는 방법이 있습니까? 아니면 내가 너를 오해 했니? –
@MariuszGrodek 왜 그렇게 생각하니? 예, 1250으로 인코딩되었으므로 1250으로 디코딩해야합니다. 그 후에 UTF-8로 인코딩 할 수 있습니다. 파일을 정상적으로 읽으려면 원래 코드를 사용하지만 이번에 UTF-8 대신 코덱으로 w1250을 사용하십시오. – Esailija
죄송합니다. 귀하의 코드를 확인한 결과 귀하는 완전히 옳았습니다! 나는이 문제에 대해 오해하고있다. 나를 위해 그것을 명확히하기위한 큰 감사. –