java怎么清空一个文件内容_如何从文本文件中删除特定内容? - java

我正在Java的SO的帮助下从事此项目的工作,正在读取一个文件夹,然后将其内容写入文件。然后,我需要浏览该内容,仅保留末尾带有Thumbnail.jpg的图像。

编辑:

public static final File outFile = new File(System.getProperty("user.home") + "/Desktop/output.txt");

public static void main(String[] args) throws IOException {

getFileContents();

}

public static void getFileContents() throws IOException{

System.out.print(outFile.getAbsolutePath());

PrintWriter out = new PrintWriter(outFile);

Files.walk(Paths.get("C:/Location")).forEach(filePath -> {

//this is where I would like to happen

if (Files.isRegularFile(filePath)) // I was thinking I could use filePath.endsWith("Thumbnail.jpg")

out.println(filePath);

});

out.close();

}

参考方案

你可以这样

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// My test file. Change to your path

File file = new File("/home/andrew/Desktop/File.txt");

if (!file.exists()) {

throw new RuntimeException("File not found");

}

try {

Scanner scanner = new Scanner(file);

//now read the file line by line...

int lineNum = 0;

while (scanner.hasNextLine()) {

String line = scanner.nextLine();

lineNum++;

// If Thumbnail.jpg is anyone where on the line

if(line.contains("Thumbnail.jpg")){

// print the line for example. You can do whatever you what with it now

System.out.println("Found item on line: " +lineNum);

}

}

} catch(FileNotFoundException e) {

//handle this

}

}

}

Java:从文件系统加载资源 - java

我的项目设定我有以下项目设置:\program.jar \images\logo.png 在我的代码中,我使用相对URL "images/logo.png"引用图像。问题如果我在目录中使用以下命令运行此程序:c:\projects\program_dir\bin\>java -jar program.jar 然后一切正常,Java能…Java-搜索字符串数组中的字符串 - java

在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…Java:线程池如何将线程映射到可运行对象 - java

试图绕过Java并发问题,并且很难理解线程池,线程以及它们正在执行的可运行“任务”之间的关系。如果我创建一个有10个线程的线程池,那么我是否必须将相同的任务传递给池中的每个线程,或者池化的线程实际上只是与任务无关的“工人无人机”可用于执行任何任务?无论哪种方式,Executor / ExecutorService如何将正确的任务分配给正确的线程? 参考方案 …对于Java中的isDirectory和isFile,文件始终返回false - java

为什么file为isFile()方法返回false,即使它是file。当它是目录时,它为isDirectory()返回false。难道我做错了什么?我测试的这些文件/目录不存在,我需要创建它们,所以这就是为什么我要测试使用createFile()还是mkdir()的原因。File file = new File("C:/Users/John/Des…JAVA:字节码和二进制有什么区别? - java

java字节代码(已编译的语言,也称为目标代码)与机器代码(当前计算机的本机代码)之间有什么区别?我读过一些书,他们将字节码称为二进制指令,但我不知道为什么。 参考方案 字节码是独立于平台的,在Windows中运行的编译器编译的字节码仍将在linux / unix / mac中运行。机器代码是特定于平台的,如果在Windows x86中编译,则它将仅在Win…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值