如何将读和强制类型转换为字符数组



我有一个源文本文件,我试图使用FileReader类的.read()方法读取字符。我已经得到了从。read中出来的整数值,并将它们转换为char,并循环输出以检查这是否有效。问题是,当我试图将它们存储在数组中时,数组打印为空。

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReversedQuotation {
public static void main(String[] args) {    
char[] charArray = new char[1000];
char[] sortedQuote = new char[1000];
int counter = 999;
int secondCounter = 0;
FileReader fr = null;

try {
fr = new FileReader("/Users/cal/Desktop/backwards.txt");
while(true) {
try {

int charInt = fr.read();
if(charInt == -1) break;
charArray[counter] = (char)charInt;
counter--;
System.out.print(charArray[counter]);
System.out.print((char)charInt); // just to check the characters are                correct.
charArray[counter] = sortedQuote[secondCounter];
secondCounter++;
System.out.print(sortedQuote[secondCounter]);
}
catch (IOException e) {
System.out.println("IO Error in reading document");
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error finding document.");
} finally {
try {
fr.close();
} catch(IOException e) {
System.out.println("Error in closing the File Reader.");
}
}
}
}

First:

charArray[counter] = (char)charInt; // say counter = 999
counter--;
System.out.print(charArray[counter]); // charArray[998]

这将打印自减索引处的值(本质上是空的),而不是赋值的索引。

charArray[counter] = (char)charInt;
System.out.print(charArray[counter]);
counter--;

这应该打印你分配的内容。

第二:
sortedQuote[secondCounter]从未被赋值,
charArray[counter] = sortedQuote[secondCounter]的赋值似乎没有任何意义。

最新更新