这是我的目录结构

在服务器内部,我有以下代码用于保存从客户端发送的文件
fileName = reader.readLine();
DataInputStream dis = null;
try {
dis = new DataInputStream(csocket.getInputStream());
FileOutputStream fos = new FileOutputStream(fileName);
buffer = new byte[4096];
int fileSize = 15123;
int read = 0;
int totalRead = 0;
int remaining = fileSize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
fos.write(buffer, 0, read);
}
fos.close();
dis.close();
} catch (IOException e) {
}
break;我想知道如何将文件保存在xml文件夹中?我尝试过使用getClass()、.getResource等方法,但似乎都不起作用。
fileName只是一个包含文件名的简单字符串,而不是路径或任何东西。
我使用下面的代码获得了正确的路径:
File targetDir = new File(getClass().getResource("xml").getPath());
File targetFile = new File(targetDir, fileName);
targetFile.createNewFile();
System.out.println(targetFile.getAbsolutePath());
dis = new DataInputStream(csocket.getInputStream());
FileOutputStream fos = new FileOutputStream(targetFile.getAbsolutePath(), false);但它仍然不能把它保存在那里...
发布于 2018-01-22 01:02:48
最好的方法是通过.properties文件或命令行参数显式接收用于存储文件的目标路径。这样,您就可以灵活地安装您的程序,并在不同的环境中进行调整。
但是,如果您希望您的程序自动采用目标目录,最好的选择是在创建FileOutputStream之前设置一个相对路径,只要您始终从相同的路径启动程序:
File targetDir=new File("xml");
File targetFile=new File(targetDir, fileName);
FileOutputStream fos = new FileOutputStream(targetFile);假设程序是从server作为当前目录启动的,这将会起作用。
更新
关于你的程序的其他次要建议:
a priori。相反,请显式检查read返回的值是否小于0 =>,这意味着文件结束reached.read的调用所需的确切数据量。只需输入缓冲区大小,因为您设置的是最大数据大小。throws子句中声明它们,并让它们通过try-with-resources指令传播到caller.尝试(新建fos =FileOutputStream FileOutputStream( ... )) { // ...使用fos...}
createNewFile。但如果您关心,请检查返回值并将consequently.分成两部分
发布于 2018-01-22 01:39:33
我尝试创建文件,但它不是在ProjectName\src\com\company\xml中创建的,而是在ProjectName\out\production\ProjectName\com\company\xml中创建的,我的代码是:
File targetDir = new File(this.getClass().getResource("xml").getPath());
// get the parent of the file
String parentPath = targetDir.getParent( );
String fileName="xml/name.txt";
//do something
File targetFile = new File(parentPath, fileName);
targetFile.createNewFile();只需注意,在编译之后,您将尝试将其保存到jar文件中,这是一件复杂的事情。通常,您需要将文件保存到jar之外的文件中(在根目录中分开),如下所示:

https://stackoverflow.com/questions/48369299
复制相似问题