[英]How to read a txt file as my system.in using eclipse
我正在解决代码厨师的问题。 我遇到了一个问题,所有问题都在于我的答案有误。 我想测试我的程序以查看其输出,但是它从文本文件读取输入,但是我不知道如何使用Eclipse来执行此操作,我的代码如下:
import java.io.*;
class Holes {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(r.readLine());
for (int i =0; i<testCases; i++)
{
int holes = 0;
String s = r.readLine();
for (int j= 0; j< s.length(); j++)
{
char c = s.charAt(j);
if (c == 'B')
holes += 2;
else if (c== 'A' || c== 'D' ||c== 'O' ||c== 'P' ||c== 'Q' ||c== 'R' )
{
holes +=1;
}
System.out.println(holes);
}
}
}
}
将文件夹添加到您的Eclipse项目中,在该文件夹中添加输入文件,然后使用BufferReader读取它,如下所示:BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
这是另一种方法,是将路径作为参数传递给程序,如下所示
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
如何在运行应用程序时执行配置并在那里找到args,您可以在其中添加任何路径,例如c:\\ myinput.txt,希望有帮助
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.