【发布时间】:2013-01-04 11:30:23
【问题描述】:
我有一个包含以下内容的文本文件:
one
two
three
four
我想通过它在Java文本文件中的位置来访问字符串“三”。我在google上找到了子字符串概念但无法使用它。
到目前为止,我能够读取文件内容:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
我想将子字符串概念应用于文件。它会询问位置并显示字符串。
String Str = new String("Welcome to Tutorialspoint.com");
System.out.println(Str.substring(10, 15) );
【问题讨论】:
-
请不要用 Reader 包装 DataInputStream。您不需要 DataInputStream 所以删除它。 vanillajava.blogspot.co.uk/2012/08/…
-
我想给程序 2 个子字符串位置,它会从文本文件中返回字符串。
-
您要输出特定的行吗?或者该位置可能不是行号?
-
不,我不想输出特定的行。例如 public class Test { public static void main(String[] args) { String str = "University"; System.out.println(str.substring(4,7)); } } 输出是“ers” 我的程序应该占据 2 个位置,并在具有该位置的文件中显示字符串。如果我放 (str.substring(4,7));根据文本文件,结果应该是“wo th”。
-
编辑您的问题以添加有关您期望什么以及您的确切问题是什么的清晰信息。尽可能窄