IO的进一步学习和多线程
Java中判断文件或文件夹是否存在
a)使用file.exists()方法即可检测file对象是否为一个有效的路径或文件夹
b)exists语法:
public boolean exists();
c)返回值
true:文件或文件夹已经存在
false:此路径不表示文件也不表示文件夹
eg:
public class Date
{
public void Discount_Information() throws IOException
{
try
{
String Date = "疯狂双十一提前开抢,购物就到京东超市购物网站,2000个品牌,5000万件爆品,全场5折封顶,速来抢购!";
File file = new File("javaio-appendfile.txt");
boolean fi = file.exists();
if(fi)
{
file.delete();
}
else
{
file.createNewFile();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//实现多线程的方法:
//1.继承 Thread 类,重写 run() 方法
package com.HSY.Example11_1;
public class Example11_1 extends Thread
{
String threadId;
public Example11_1()
{
}
public Example11_1(String threadId)
{
this.threadId = threadId;
}
@Override
public void run()
{
System.out.println("Thread started:" + this.threadId);
for (int i = 0;i < 6;i++)
System.out.print("i=" + (i + 1) + "\t");
System.out.println("Thread stopped:" + this.threadId);
}
}
package com.HSY.Test;
import com.HSY.Example11_1.Example11_1;
public class Test
{
public static void main(String[] args)
{
System.out.println("Starting ThreadTest1");
Example11_1 t1 = new Example11_1("thread1");
t1.start();
Example11_1 t2 = new Example11_1("thread2");
t2.start();
Example11_1 t3 = new Example11_1("thread3");
t3.start();
System.out.println("ThreadTest1 is done");
}
}
//2.实现 Runnable 接口,重写 run() 方法
package com.HSY.Example11_2;
public class Example11_2 implements Runnable
{
String threadId;
public Example11_2()
{
}
public Example11_2(String threadId)
{
this.threadId = threadId;
}
@Override
public void run()
{
System.out.print("\n Thread started: " + this.threadId);
for(int i = 0;i < 6;i++)
{
System.out.print("i = " + (i + 1) + "\t");
}
System.out.print(" \n Thread stopped :" + this.threadId);
}
}
package com.HSY.Test;
import com.HSY.Example11_2.Example11_2;
public class Test
{
public static void main(String[] args)
{
System.out.println("Starting ThreadTest1");
Runnable r1 = new Example11_2("thread1");
Thread t1 = new Thread(r1);
t1.start();
Runnable r2 = new Example11_2("thread2");
Thread t2 = new Thread(r2);
t2.start();
Runnable r3 = new Example11_2("thread3");
Thread t3 = new Thread(r3);
t3.start();
System.out.print("ThreadTest1 is done");
}
}
//3.实现 Callable 接口,重写 call() 方法
//第三种方法暂时有点问题没有实现,暂时不展示
运行结果:(不唯一)
学习来源:来源一