一道 程序题!!

wang303044 2005-06-16 12:26:50
用java实现在一个文本文件中查找指定的字符串, 如命令 java Search "good" data.txt

则实现在data.txt中查找"good" 如果找到就返回所在行数和该行内容,

若不止一行则打印出所有这样的行。
...全文
106 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
rower203 2005-06-16
  • 打赏
  • 举报
回复
加入行号:
public static void find(String content, String file){
BufferedReader readFile;
File f = new File(file);
if(!f.exists()){
System.out.println(file + " not exist!");
return;
}
try {
readFile = new BufferedReader(
new FileReader(file));

String line;
try {
int lineNum = 0;
line = readFile.readLine();
while(line != null) {
lineNum++;
if(line.indexOf(content) >= 0)
System.out.println("Line " + lineNum + ": " + line);
line = readFile.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
// find("good", "data.txt");
find(args[0], args[1]);
}
rower203 2005-06-16
  • 打赏
  • 举报
回复
public static void main(String args[])
{
find(args[0], agrs[1]);
}
rower203 2005-06-16
  • 打赏
  • 举报
回复
public static void find(String content, String file){
BufferedReader readFile;
File f = new File(file);
if(!f.exists()){
System.out.println(file + " not exist!");
return;
}
try {
readFile = new BufferedReader(
new FileReader(file));

String line;
try {
line = readFile.readLine();
while(line != null) {
if(line.indexOf(content) >= 0)
System.out.println(line);
line = readFile.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
find("good", "data.txt");
}
Z_Beginner 2005-06-16
  • 打赏
  • 举报
回复
import java.io.*;

public class test
{
public static void main(String args[])
{
char ch;
int chi;
int ox;
File MyFile1=new File("c:\\temp",args[1]+".txt");
String sub=args[0];
StringBuffer sb=new StringBuffer();
try
{
FileInputStream fin=new FileInputStream(MyFile1);
while((chi=fin.read())!=-1)
{
//System.out.print((char)chi);
sb.append((char)chi);
}
fin.close();
System.out.println(sb);
}
catch(FileNotFoundException e){System.err.println(e);}
catch(IOException e){System.err.println(e);}
String s=sb.toString();
for(int i=0;i<s.length();)
{
ox=s.indexOf(sub,i);
System.out.println(s.substring(ox,ox+3));
i=ox+3;
}
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧