java - 有关检索正在处理的文件的名称并将处理后的行写入新文件的问题

标签 java

目前,我已经编写了一个代码段,可以从文件夹中读取文件,并逐行读取每个文件并替换一些无用的字符。

File[] files = dir.listFiles();
FileInputStream    fis;
BufferedReader br;
String   line;
for (File file : files) {
  fis = new FileInputStream(file);
  br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
  while ((line = br.readLine()) != null) {
           System.out.println("Before: "+line);        
               String templine = line.replaceAll("[a-zA-Z0-9]", "");
           System.out.println("After: "+templine);
  };

现在我有两个问题:

我需要将这些处理过的行写入另一个备份文件,该文件与原始文件同名,但将放置在另一个目录中。

因此,第一个问题是如何获取原始文件的名称?

第二个问题是如何创建一个具有给定名称的文件并将这些处理过的行写入该文件中。

最佳答案

getNameFile类下的一个方法,用于获取文件名。

来自javadocs :

public String getName()

Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.

要创建具有名称的文件,请使用 File constructor正如这里提到的:

public File(String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

关于java - 有关检索正在处理的文件的名称并将处理后的行写入新文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298463/

相关文章:

java - 用 Java 计算矩阵的零空间基

java - 如何让我的程序让用户在运行其余代码之前在 JtextField 中输入文本? (Java 8)

Java 验证 - 将 @Valid 约束添加到自定义约束会引发 "@Valid is not applicable to annotation type"

java - 在 twitter4j 的 ResponseList 上使用 .add() 方法?

java - 我的 display() 未运行或未显示我的 println

java - 如何修复 org.json.JSONException : on Volley?

Java:在列表中添加或删除元素时避免使用 'instanceof'

java - 我可以将正则表达式与 Stacks 一起使用吗?

java - 无法在 Intellij 中导入 Maven 模块

java - 从数据库设计决策中导出 XML、JSON