Java:命令行/文件的输入输出

命令行的输入和输出

package com.example;

import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        // 读取命令行输入
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        // 向命令行输出
        System.out.printf("input: %s", input);
    }
}

输入hello执行结果

$ hello
input: hello

文件的输入输出

package com.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        // 读取文件输入
        Scanner scanner = new Scanner(new File("input.txt"));

        // 输出到文件
        PrintWriter writer = new PrintWriter("output.txt");

        // 按行读取,按行输出
        while (scanner.hasNextLine()) {
    
    
            writer.println(scanner.nextLine());
        }

        scanner.close();
        writer.close();
    }
}

获取启动目录

package com.example;

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        // 获取启动目录
        String dir = System.getProperty("user.dir");
        System.out.println(dir);
    }
}

猜你喜欢

转载自blog.csdn.net/mouday/article/details/130904968
今日推荐