我是java编程的新手我需要一个程序从文件中读取某些信息并选择所需的特定信息,然后将这些特定信息写入文本文件。
{
BufferedReader in = new BufferedReader (newFileReader("C:/Users/ngorentl/"));
String info = "";
String info1 = "";
int startLine = 111 ;
int endLine = 203 ;
int sl = 221;
int el =325;
//仅读取所需的特定信息并在控制台中打印
for (int i = 0; i < startLine; i++) { info = in.readLine(); }
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
}
for (int j = 203; j < sl; j++) { info1 = in.readLine(); }
for (int j = sl; j < el + 1; j++) {
info1 = in.readLine();
System.out.println(info1);
}
// having a problem from here i dont know whether this is the correct approach
File fin = new File(info); // getting an error here
FileInputStream fis = new FileInputStream(fin);
BufferedReader is = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream("hh.txt");
OutputStreamWriter osw= new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
String aLine = null;
while ((aLine = is.readLine()) != null) {
bw.write(aLine);
bw.newLine();
bw.flush();
bw.close();
is.close();
}
in.close();
}
答案 0 :(得分:0)
File fin = new File(String fileName)是正确的语法。 例如。 File fin = new File(“C:\ abc.txt”);
[UPDATE] 假设您的问题是关于将String写入文件。 在Java 7中
try( PrintWriter out = new PrintWriter( "filename.txt" ) ){
out.println( info);
}
在Java 6或更低版本中,使用
try {
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(info);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
并且可能更正您的代码,因此可变信息包含所有信息
for (int i = startLine; i < endLine + 1; i++) {
info += in.readLine();
}
System.out.println(info);