본문 바로가기
JAVA/문법, Collection

JAVA input.txt 파일경로 설정

by wanna_dev 2024. 1. 11.

코딩테스트 문제를 풀 경우 input이 txt파일로 되어 편하게 설정할 수 있는 방법을 배웠다.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Solution{
	public static void main(String[] args) throws IOException {
		String path = System.getProperty("user.dir")+ "\\src\\";
		System.setIn(new FileInputStream(path+"input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		String s = br.readLine();
		StringTokenizer st = new StringTokenizer(s);
		bw.write(st.nextToken());
		bw.flush();
	}
}

 

다음과 같이 System.getProperty로 현재 working directory 을 얻어오고 source파일이 있는 경로까지 추가해준 후, setIn을 통해서 File을 읽어오면 된다.

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Solution{
	static int[][] graph = new int[20][20];
	public static void main(String[] args) throws IOException {
		String path = System.getProperty("user.dir")+ "\\src\\";
		System.setIn(new FileInputStream(path+"input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		String s = br.readLine();
		//System.out.println(s);
		
		
		int N,K,tc;
		
		tc = Integer.parseInt(s);
		
		
		for(int test_case = 1; test_case<=tc; test_case++)
		{	
			s = br.readLine(); // Read the next line for each test case
		    StringTokenizer st = new StringTokenizer(s); // Create a new StringTokenizer for each test case

		    
			N = Integer.parseInt(st.nextToken());
			K = Integer.parseInt(st.nextToken());
			//System.out.println(N+" "+K);
			
			for(int i=0; i<N; i++) {
				s = br.readLine();
				st = new StringTokenizer(s);
				for(int j=0; j<N; j++) {
					graph[i][j] = Integer.parseInt(st.n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5 0

'JAVA > 문법, Collection' 카테고리의 다른 글

JAVA ASCII trick  (0) 2024.01.13
JAVA abs function  (0) 2024.01.13
자바 입출력 정리(BufferedReader/Writer ,Scanner, System.out.print)  (1) 2024.01.11