简体   繁体   中英

How can I write to a file in linux using java code which runs on my windows machine?

My application server is hosted in Linux having Tomcat Server. I want to change some files through Java code that is running on my windows machine. How can I do it? I know how to connect to Linux through Java, but don't know about the command that used to write, append or clear the files.

Many thanks!

You can do that with external library JSch . The below should do the job.

JSch jsch = new JSch();
Session session = jsch.getSession("remote_user_name", "remote_host_or_ip", 22); // 22 for SFTP
session.setPassword("remote_password");


java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

session.connect(10000);
Channel channel = session.openChannel("sftp");
channel.connect();

System.out.println("Connection Opened");
ChannelSftp channelSftp = (ChannelSftp) channel;
InputStream inputStream = new FileInputStream("text_file.txt");
channelSftp.put(inputStream, "/remote/folder/file_to_be_rewritten.txt");

System.out.println("File should be uploaded");

channelSftp.disconnect();
session.disconnect();

Your server should provide a REST API to allow the file to be modified via a HTTP request. This way, you can manage all updates to the file, and prevent the file being corrupted by attempts to make multiple concurrent updates, using synchronized blocks, locks or actors.

However, you should also consider storing the contents of the file in a database (SQL or NoSQL) instead of a file. This would handle concurrency control in an easier-to-manage way, especially if the update was atomic (one row or one document).

If you are trying to perform file operations using Java, check out this tutorial and documentation on reading, writing, creating, and opening files.

Here is sample code that reads from a file, and writes to a file.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;

public class FileOps {

    public static void main(String[] args) {
        readFile();
        writeFile();
    }

    private static void readFile() {
        Charset charset = Charset.forName("US-ASCII");
        try (BufferedReader reader = Files.newBufferedReader(FileSystems.getDefault().getPath("/path/on/disk/file1.txt"), charset)) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }

    private static void writeFile() {
        Charset charset = Charset.forName("US-ASCII");
        String s = "Sample Java Code";
        try (BufferedWriter writer = Files.newBufferedWriter(FileSystems.getDefault().getPath("/path/on/disk/file2.txt"), charset)) {
            writer.write(s, 0, s.length());
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM