Javaを使用してフォルダ内のすべてのファイルを単一のファイルに読み取る方法は?
listFiles() ファイルのメソッド classは、現在の(File)オブジェクトによって表されるパス内のすべてのファイル(およびディレクトリ)のオブジェクト(抽象パス)を保持する配列を返します。
フォルダ内のすべてのファイルの内容を1つのファイルに読み込むには-
- 必要なファイルパスをパラメータとして渡して、ファイルオブジェクトを作成します。
- スキャナーまたはその他のリーダーを使用して、各ファイルの内容を読み取ります。
- 読み取った内容をStringBufferに追加します。
- StringBufferの内容を必要な出力ファイルに書き込みます。
例
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\\SampleDirectory");
//List of all files and directories
File filesList[] = directoryPath.listFiles();
System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
StringBuffer sb = new StringBuffer();
for(File file : filesList) {
System.out.println("File name: "+file.getName());
System.out.println("File path: "+file.getAbsolutePath());
System.out.println("Size :"+file.getTotalSpace());
//Instantiating the Scanner class
sc= new Scanner(file);
String input;
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input+" ");
}
System.out.println("Contents of the file: "+sb.toString());
System.out.println(" ");
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:\\output.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.write(sb.toString().getBytes());
outputStream.flush();
System.out.println("Data entered into the file");
}
}
} 出力
List of files and directories in the specified directory: File name: sample1.txt File path: D:\SampleDirectory\sample1.txt Contents of the file: sample text file1 Data entered into the file File name: sample2.txt File path: D:\SampleDirectory\sample2.txt Contents of the file: sample text file2 Data entered into the file File name: sample3.txt File path: D:\SampleDirectory\sample3.txt Contents of the file: sample text file3 Data entered into the file
-
Javaを使用してJSONファイルを作成/作成する方法は?
JSONまたはJavaScriptObjectNotationは、人間が読める形式のデータ交換用に設計された、軽量のテキストベースのオープンスタンダードです。 JSONで使用される規則は、C、C ++、Java、Python、Perlなどを含むプログラマーに知られています。サンプルJSONドキュメント − { "book": [ { "id": "01",
-
ディレクトリの下にあるすべてのExcelファイルをPandasDataFrameとして読み取る方法は?
ディレクトリ内のすべてのExcelファイルを読み取るには、Globモジュールとread_excel()メソッドを使用します。 次がディレクトリ内のExcelファイルであるとしましょう- Sales1.xlsx Sales2.xlsx 最初に、すべてのExcelファイルが配置されているパスを設定します。 Excelファイルを取得し、globを使用してそれらを読み取ります- path =C:\\ Users \\ amit _ \\ Desktop \\ files =glob.glob(path + \ *。xlsx)print(ファイル名:、ファイル名) 次