简体   繁体   中英

Writing to a file in the current directory in java

import java.io.*;
import java.lang.*;
import java.net.*;
import java.util.*;
public class Solution{
    public static void main(String args[])throws IOException{
        int max=10;
        URL path = Solution.class.getResource("output.txt");
        File output = new File(path.getFile());
        BufferedWriter writer = new BufferedWriter(new FileWriter(output));
        writer.write(Integer.toString(max));
        writer.close();

    }
}

I was trying to write data to an output.txt file which is current directory.The program has no erros but max value is not getting written on the output.txt file. Thank you in advance.

create a new folder and keep your java and output.txt file inside the folder then compile and run the program. Hope it will solve your problem

If you want to access the current directory you should reference the file directly, and use try with resources to clean up the output stream:

public static void main(String args[]) throws IOException {
    int max=10;
    File output = new File("output.txt");
    System.out.println("Writing to: "+output.getAbsolutePath());
    try(BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
        writer.write(Integer.toString(max));
    }
}

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