@肖国颖先生,您好,想跟你请教个问题:一个简单的java程序,定时扫描某个文件夹里面的文件,若是不输入则扫描默认路径,但是输入路径的话,则扫描该路径,利用您写的那段代码,怎么获得从控制台输入的路径呢?我试着在改了一下代码,可是还是不行,您能帮我看看么??
public class TestTimeout {
public static void main(String[] args) {
final TestTimeout testTimeout = new TestTimeout();
boolean doClean = testTimeout.readInput();
if (doClean) {
System.out.println("The database was cleaned!");
}else {
System.out.println("The clean operation was ignored.");
}
}
public int readInputStreamWithTimeout(InputStream is, byte[] buf, int timeoutMillis)
throws IOException {
BufferedReader buffer1 = new BufferedReader(new InputStreamReader(is));
input = buffer1.readLine(); //读取输入数据
int bufferOffset = 0; //读取数据buf偏移量
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;//计算过期时间
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < buf.length) {
int readLength = Math.min(is.available(), buf.length - bufferOffset);
int readResult = is.read(buf, bufferOffset, readLength);
if (readResult == -1) {//流结束直接结束
break;
}
bufferOffset += readResult;
if (readResult > 0) { //读取到内容结束循环
break;
}
try {
Thread.sleep(10); //等待10ms读取,减小cpu占用
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return bufferOffset;
}
public boolean readInput() {
System.out.println("Do you want to clean and initialize the database?(y/n)");
boolean doClean = false;
byte[] inputData = new byte[1];//设置为1,只读第一个字符
int readLength = 0;
try {
InputStream input=System.in;
readLength = readInputStreamWithTimeout(input, inputData, 6000
} catch (IOException e) {
e.printStackTrace();
}
if (readLength > 0) {
switch ((char) inputData[0]) { //读取按键
case 'y':
case 'Y': {
doClean = true; //设置返回为true
break;
}
}
}
return doClean;
}
}
这代码,能格式化下么,实在没有心情看下去。######代码见 http://my.oschina.net/noahxiao/blog/157090######其实我原来是只接收一个char,你可以修改为接收整行内容
byte[] inputData = new byte[1];//设置为1,只读第一个字符 int readLength = 0; try { InputStream input=System.in; readLength = readInputStreamWithTimeout(input, inputData, 6000 } catch (IOException e) { e.printStackTrace(); }
byte[] inputData = new byte[1024]; String inputString=null;
int readLength = 0;
try {
readLength = readInputStreamWithTimeout(System.in, inputData, 3000);
inputString=new String(Arrays.copyOf(inputData,readLength));//由于与控制台编码一致所以new String没有加编码
} catch (IOException e) {
e.printStackTrace();
}</pre>
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。