j2me中读写文件查找的实例

本文介绍了一个使用Java实现的简单字符串搜索算法,该算法能够在指定文件中查找特定的字符串,并返回字符串的位置及其所在的行号。通过读取文件内容到字节数组中,再利用双重循环匹配目标字符串,实现了基本的文本搜索功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

String word_input = "wrap";
String word_search = null;

private void search ()
{
InputStream in = null;
byte[] buffer1 = new byte[259737];
byte[] word = new byte[20];
//System.out.println(word.length);
int kk = 0;
int position = 0;
int line = 1;
int temp_line = 100000;
int flag = 0;
try
{
word = word_input.getBytes();
//System.out.println(word.length);
in = getClass().getResourceAsStream("/cet4.txt");
in.read(buffer1);
//System.out.println(buffer1.length);
in.close();
}
catch (Exception e)
{
System.out.println("error!");
}
for (int ii = 0; ii < buffer1.length - 20; ii++)
{
if (buffer1[ii] == '/n')
{
line++;
}
for (int jj = 0; jj < word.length; jj++)
{
if (buffer1[ii + jj] == word[jj])
{
kk++;
}
}
if (kk == word.length)
{
if (flag == 0)
{

position = ii;
try
{
word_search = new String(buffer1, position, word.length, "UTF-8");
}
catch (Exception e)
{
System.out.println("new string() error");
}
System.out.println(word_search);
System.out.println(line);
temp_line = line;
//break;
flag ++ ;
}
}
else
{
kk = 0;
}
if (line == temp_line + 1)
{
try
{
word_search = new String(buffer1, position + word.length + 1, ii - position - word.length - 2, "UTF-8");
}
catch (Exception e)
{
}
System.out.println(word_search);
break;
}
if (ii == buffer1.length - 21)
{
System.out.println("no word");
break;
}
}

} // search() end!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值