在 groovy 中复制没有空白字符的文件的最佳方法是什么
What is the best way to copy file without blank characters in groovy
我必须做一个 exercise.I 需要通过擦除空白将文件复制到另一个文件中 characters.I 已完成以下操作。
有没有人有更好的解决方案?
class Exercise4 {
static void main(String... args) {
Exercise4 ex = new Exercise4()
ex.copyWithoutBlank("C:\Users\drieu\tmp\test.txt")
}
def copyWithoutBlank(String filePath) {
File file = new File(filePath)
File fileWithoutBlank = new File("C:\Users\drieu\tmp\test2.txt")
PrintWriter printerWriter = new PrintWriter(fileWithoutBlank)
file.eachLine { line ->
println "line:" + line
String lineWithoutBlank = line.replaceAll(" ", "")
println "Copy line without blank :" + lineWithoutBlank + " into file:" + fileWithoutBlank.name
printerWriter.println(lineWithoutBlank)
}
printerWriter.close()
}
}
提前致谢,
您可以在 File
上使用 withWriter
方法打开编写器,完成后关闭它:
class Exercise4 {
static main(args) {
Exercise4 ex = new Exercise4()
ex.copyWithoutBlank('/tmp/test.txt')
}
void copyWithoutBlank(String filePath) {
new File('/tmp/test2.txt').withWriter { w ->
new File(filePath).eachLine { line ->
w.writeLine line.replaceAll(' ', '')
}
}
}
}
我必须做一个 exercise.I 需要通过擦除空白将文件复制到另一个文件中 characters.I 已完成以下操作。 有没有人有更好的解决方案?
class Exercise4 {
static void main(String... args) {
Exercise4 ex = new Exercise4()
ex.copyWithoutBlank("C:\Users\drieu\tmp\test.txt")
}
def copyWithoutBlank(String filePath) {
File file = new File(filePath)
File fileWithoutBlank = new File("C:\Users\drieu\tmp\test2.txt")
PrintWriter printerWriter = new PrintWriter(fileWithoutBlank)
file.eachLine { line ->
println "line:" + line
String lineWithoutBlank = line.replaceAll(" ", "")
println "Copy line without blank :" + lineWithoutBlank + " into file:" + fileWithoutBlank.name
printerWriter.println(lineWithoutBlank)
}
printerWriter.close()
}
}
提前致谢,
您可以在 File
上使用 withWriter
方法打开编写器,完成后关闭它:
class Exercise4 {
static main(args) {
Exercise4 ex = new Exercise4()
ex.copyWithoutBlank('/tmp/test.txt')
}
void copyWithoutBlank(String filePath) {
new File('/tmp/test2.txt').withWriter { w ->
new File(filePath).eachLine { line ->
w.writeLine line.replaceAll(' ', '')
}
}
}
}