I have a difficulty to change permission of existing file. What I want to do is, marshall xml and write it to a file. Because the apps is running under 'root' account, then the file is owned by root. I want to change permission of this file, so other user can SFTP this file.
This is my first code:
File file = new File(Constant.fileName);
context = JAXBContext.newInstance(RateGroups.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE);
marshaller.marshal(rateGroups, file);
marshaller.marshal(rateGroups,System.out);
If I run code above, the file written successfully, but I can't SFTP using other account (permission denied). Then I add this code to change permission of the file:
file.setWritable(true,false);
file.setExecutable(true,false);
file.setReadable(true,false);
The permission has been changed, but the file size also became zero (0). Can please tell me how to change it permission or maybe change the owner if possible? Thank you.
UPDATE 1
After writing a file, I call my sftp class:
SFTPFile sftpFile = new SFTPFile();
error = sftpFile.execute(Constant.rateGroupxml);
This is code in SFTPFile class:
public int execute(String fileName){
JSch jsch = new JSch();
Session session = null;
int result = 0;
String localPath = Constant.path + "/report/" + fileName;
//try {
try {
session = jsch.getSession(Constant.user1, Constant.IP1, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(Constant.pass1);
session.connect();
System.out.println("session: " + session.getUserName());
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(Constant.pathDestination);
sftpChannel.put(localPath);
sftpChannel.exit();
session.disconnect();
result = 0;
} catch (SftpException ex) {
Logger.getLogger(SFTPFile.class.getName()).log(Level.SEVERE, null, ex);
result = 1;
} catch (JSchException ex) {
Logger.getLogger(SFTPFile.class.getName()).log(Level.SEVERE, null, ex);
result = 2;
}
return result;