我需要使用多个线程读取两个文件,并在控制台中打印文件的内容。用户将输入文件路径并使用线程读取文件的内容。我很难理解文件。谁能建议我在 run 方法中应该做什么?
import java.io.*;
public class Ch3Ex4 implements Runnable
{
public void ReadFile(String str,Thread thread)
{
try
{
File inputFile = new File(str);
FileInputStream in = new FileInputStream(inputFile);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
}
public static void main (String[] args)
{
try
{
Ch3Ex4 obj = new Ch3Ex4();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the two file paths:");
String s1 = br.readLine();
String s2 = br.readLine();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);
obj.ReadFile(s1, thread1);
obj.ReadFile(s2, thread2);
thread1.start();
thread2.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
最佳答案
run
方法旨在包含由该线程执行的代码。因此,当您想要从两个不同的线程读取两个文件时,您需要使用 run
来执行您在 ReadFile
方法中所做的任何操作。
请注意,您需要创建 Ch3Ex4
类的实例并调用 start
方法才能开始启动新线程。
编辑:在这种情况下,您可以在 run
方法中使用 BufferedReader
,如下所示:(来自 mkyong 的网站)
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();
}
}
关于java - 文件和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14303050/