我正在做一个简单的练习,其中程序从 .dat 文件读取数据并将其打印在控制台上。
我正在使用 NetBeans。我将 .dat 文件保存在主文件所在的默认包文件夹中。并且找不到 .dat 文件。
代码如下:
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.io.*;
public class BufferConverter {
public static void main(String[] arguments) {
try {
// read byte data into a byte buffer
String data = "friends.dat";
FileInputStream inData = new FileInputStream(data);
FileChannel inChannel = inData.getChannel();
long inSize = inChannel.size();
ByteBuffer source = ByteBuffer.allocate( (int) inSize );
inChannel.read(source, 0);
source.position(0);
System.out.println("Original byte data:");
for (int i = 0; source.remaining() > 0; i++) {
System.out.print(source.get() + " ");
}
// convert byte data into character data
source.position(0);
Charset ascii = Charset.forName("US-ASCII");
CharsetDecoder toAscii = ascii.newDecoder();
CharBuffer destination = toAscii.decode(source);
destination.position(0);
System.out.println("\n\nNew character data:");
for (int i = 0; destination.remaining() > 0; i++) {
System.out.print(destination.get());
}
System.out.println();
} catch (FileNotFoundException fne) {
System.out.println(fne.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
我应该写一个具体的路径吗?如何让程序找到.dat 文件?
非常感谢西尔万的任何帮助
最佳答案
I am working with NetBeans. I saved the .dat file in the default package folder where the main file is located. And it cannot find the .dat file.
大概该文件夹与启动时的工作目录不同。
使用System.out.println(new File(".").getAbsolutePath());
查看您正在运行的位置,然后使用与之相关的文件名,或者找出如何说服 Netbeans 将文件复制到适当的位置(例如,将其放在 resources
目录中,我认为该目录算作资源复制)。
关于java - 主类找不到 .dat 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529314/