Java 读取和返回多个bin文件
该代码段实际上应该读取指定路径中的所有bin文件,并最终将其转换为字符串,并将所有转换为字符串的Java 读取和返回多个bin文件,java,Java,该代码段实际上应该读取指定路径中的所有bin文件,并最终将其转换为字符串,并将所有转换为字符串的字节[]作为不同的字符串元素存储在字符串[]中,返回字符串[]。尽管由于计数器的原因,它读取了所有bin文件,但不知何故,它只返回它读取的第一个二进制文件的字符串 即使是这个修改过的版本似乎也能起作用。我猜它会读取所有bin文件,但只返回上次读取的bin文件的字符串。我尝试的是将所有字符串元素存储到string[]并将string[]返回给另一个调用函数 private static int
字节[]
作为不同的字符串元素存储在字符串[]
中,返回字符串[]
。尽管由于计数器的原因,它读取了所有bin文件,但不知何故,它只返回它读取的第一个二进制文件的字符串
即使是这个修改过的版本似乎也能起作用。我猜它会读取所有bin文件,但只返回上次读取的bin文件的字符串。我尝试的是将所有字符串元素存储到string[]
并将string[]
返回给另一个调用函数
private static int count = 0;
public static String[] play()throws Exception{
File file=new File("E:/proj/"+count+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+count+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
String[] args=new String[]{word};
count++;
return args ;
}
如果我清楚了解您的要求,您可以尝试通过以下方式更改代码:
public static String[] play(){
int i = 1;
String[] args=null;;
String result = null;
while (true) {
try {
result += processFile(i++);
args=new String[]{result};
}
catch (Exception e) {
System.out.println("No more files");
break;
}
}
return args;
}
private static String processFile(int fileNumber) throws Exception {
File file=new File("E:/proj/"+fileNumber+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+fileNumber+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned, to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
return word;
}
List args=new ArrayList();
while(true){
试一试{
add(processFile(i++);
}
捕获(例外e){
//你的代码
}
}
字符串[]数组=args.toArray(新字符串[0]);
您刚刚发布的代码中有几个问题:
-结果被初始化为null,所以代码将在第一个循环中抛出一个NPE。
-假设您正确地初始化了它(在您的例子中为“”),args将重新分配到每个循环上的一个新数组,因此您将丢失从上一个循环获得的信息
如果希望play()
方法返回一个数组,其中数组中的每个项都是一个文件的内容,那么应该可以这样做。如果你想要一些不同的东西,你需要更清楚地解释你的需求
List<String> args = new ArrayList<String>();
while (true) {
try {
args.add(processFile(i++));
}
catch (Exception e) {
// your code
}
}
String[] array = args.toArray(new String[0]);
公共静态字符串[]play(){
int i=1;
列表文件=新的ArrayList();
while(true){
试一试{
添加(processFile(i++);
}捕获(例外e){
System.out.println(“不再有文件”);
打破
}
}
返回files.toArray(新字符串[0]);
}
是否从循环中调用play()方法?你能显示代码的其余部分吗?hii Assylias..play方法不是从循环中调用的。它只是在另一门课中被称为…@kuki,如果它能帮助你解决问题,别忘了“接受答案”,否则你的接受率会下降。
public static String[] play() {
int i = 1;
List<String> files = new ArrayList<String>();
while (true) {
try {
files.add(processFile(i++));
} catch (Exception e) {
System.out.println("No more files");
break;
}
}
return files.toArray(new String[0]);
}