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…
總結
以上是生活随笔為你收集整理的java怎么清空一个文件内容_如何从文本文件中删除特定内容? - java的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win7系统补丁怎么安装?Win7系统补
- 下一篇: java怎样返回json_java怎么返