Java
- for (File file : new File("/tmp").listFiles()) {
- System.out.println(file);
- }
- Path dir = Path.of("/tmp");
- try (Stream<Path> stream = Files.list(dir)) {
- stream.forEach(System.out::println);
- }
Groovy
- new File('/tmp').eachFile { println it }
Kotlin
- File("/tmp").listFiles().forEach(::println)
- val path = Path.of("/tmp")
- Files.list(path).use { it.forEach(::println) }
Scala
- new File("/tmp").listFiles.foreach(println)
scala-io を使った場合
- for (path <- Path("/tmp") * All) println(path.name)
Erlang
- lists:foreach(fun(File) -> io:format("~s~n", [File]) end, filelib:wildcard("/tmp/*")).
Haskell
- getDirectoryContents "/tmp" >>= mapM_ putStrLn
- contents <- getDirectoryContents "/tmp"
- mapM_ putStrLn contents
PowerShell
- $dir = [System.IO.DirectoryInfo] '/tmp'
- $dir.GetFiles() + $dir.GetDirectories() | foreach { $_.FullName }
- $dir = [System.IO.DirectoryInfo] '/tmp'
- @($dir.GetFiles(); $dir.GetDirectories()) | foreach { $_.FullName }
F#
- let files = Directory.EnumerateFileSystemEntries "/tmp"
- for file in files do printfn "%s" file
- let dir = new DirectoryInfo "/tmp"
- for file in dir.EnumerateFileSystemInfos() do printfn "%s" file.FullName
- let dir = new DirectoryInfo "/tmp"
- let files = seq<FileSystemInfo> {
- yield! Seq.cast <| dir.GetFiles()
- yield! Seq.cast <| dir.GetDirectories()
- }
- for file in files do printfn "%s" file.FullName
C#
- var files = Directory.EnumerateFileSystemEntries("/tmp");
- foreach (var file in files) {
- Console.WriteLine(file);
- }
- var dir = new DirectoryInfo("/tmp");
- foreach (var file in dir.EnumerateFileSystemInfos()) {
- Console.WriteLine(file.FullName);
- }
C++
- #include <dirent.h>
- if (DIR* dir = opendir("/tmp")) {
- while (struct dirent* ent = readdir(dir)) {
- string name = ent->d_name;
- if (name != "." && name != "..") {
- cout << name << endl;
- }
- }
- closedir(dir);
- }
Boost を使った場合
- #include <boost/filesystem/operations.hpp>
- directory_iterator end;
- for (directory_iterator it(path("/tmp")); it != end; it++) {
- cout << it->path().filename().string() << endl;
- }
Go
- files, err := ioutil.ReadDir("/tmp")
- if err != nil { return err }
- for _, file := range files {
- fmt.Printf("%s\n", file.Name())
- }
- dir, err := os.Open("/tmp")
- if err != nil { return err }
- defer dir.Close()
- files, err := dir.Readdir(-1)
- if err != nil { return err }
- for _, file := range files {
- fmt.Printf("%s\n", file.Name())
- }
Rust
- let entries = fs::read_dir("/tmp").unwrap();
- for entry in entries {
- println!("{}", entry.unwrap().file_name().to_string_lossy());
- }
TypeScript
Node.js の場合
- let files = fs.readdirSync('/tmp');
- for (let i in files) {
- console.log(files[i]);
- }
JavaScript
Node.js の場合
- let files = fs.readdirSync('/tmp');
- for (let i in files) {
- console.log(files[i]);
- }
CoffeeScript
Node.js の場合
- for file in fs.readdirSync '/tmp'
- console.log file
Ruby
- puts Dir.children('/tmp')
- Dir.each_child('/tmp') {|f| puts f }
Python
- for f in os.listdir('/tmp'):
- print(f)
- for f in glob.glob('/tmp/*'):
- print(f)
- for f in pathlib.Path('/tmp').iterdir():
- print(f)
PHP
- foreach (glob('/tmp/*') as $f) {
- echo $f, "\n";
- }
Perl
- for (glob '/tmp/*') {
- print $_, "\n";
- }
- print $_, "\n" for glob '/tmp/*'
Java
Java 16以降
- public static List<Path> getAllFiles(Path path) throws IOException {
- try (Stream<Path> stream = Files.walk(path)) {
- return stream.filter(Files::isRegularFile).toList();
- }
- }
Java 15まで
- public static List<Path> getAllFiles(Path path) throws IOException {
- try (Stream<Path> stream = Files.walk(path)) {
- return stream.filter(Files::isRegularFile).collect(Collectors.toList());
- }
- }
Groovy
- def getAllFiles(File file) {
- file.directory ?
- file.listFiles().collect { getAllFiles it }.flatten() :
- [file]
- }
- def getAllFiles(File dir) {
- def result = dir.listFiles() as List
- dir.eachDirRecurse { subdir ->
- subdir.listFiles().each { result << it }
- }
- result.findAll { it.file }
- }
- def getAllFiles(Path path) {
- def stream = Files.walk path
- try {
- stream.filter { Files.isRegularFile(it) }.collect Collectors.toList()
- } finally {
- stream.close()
- }
- }
Groovy 3.0以降
- def getAllFiles(Path path) {
- try (def stream = Files.walk path) {
- stream.filter(Files::isRegularFile).collect Collectors.toList()
- }
- }
Kotlin
- fun getAllFiles(path: Path) = Files.walk(path).use {
- it.filter { ! Files.isDirectory(it) }.toList()
- }
- fun getAllFiles(file: File): Sequence<File> {
- return file.listFiles().asSequence().flatMap {
- if (it.isDirectory) getAllFiles(it) else sequenceOf(it)
- }
- }
Scala
- def getAllFiles(file: File): Seq[File] =
- if (file.isDirectory) file.listFiles.toSeq.flatMap(getAllFiles) else Seq(file)
- def getAllFiles(file: File): Seq[File] = file.isDirectory match {
- case true => file.listFiles.toSeq.flatMap(getAllFiles)
- case false => Seq(file)
- }
scala-io を使った場合
- def getAllFiles(dir: Path) = dir ** IsFile
Erlang
- get_all_files(Dir) -> filelib:fold_files(Dir, "", true, fun(File, List) -> [File|List] end, []).
Haskell
- getAllFiles dir = do
- contents <- catch (getDirectoryContents dir) (\ _ -> return [])
- let contents' = [dir ++ "/" ++ path | path <- contents, notElem path [".", ".."]]
- contents'' <- mapM getAllFiles contents'
- return $ contents' ++ concat contents''
PowerShell
- function getAllFiles([System.IO.DirectoryInfo] $dir) {
- $dir.GetFiles()
- $dir.GetDirectories() | foreach { getAllFiles($_) }
- }
F#
- let rec getAllFiles dir = seq {
- yield! Directory.EnumerateFiles dir
- for subdir in Directory.EnumerateDirectories dir do yield! getAllFiles subdir
- }
- let rec getAllFiles (dir : DirectoryInfo) = seq {
- yield! dir.EnumerateFiles()
- for subdir in dir.EnumerateDirectories() do yield! getAllFiles subdir
- }
- let getAllFiles dir =
- let generator = function
- | [] -> None
- | head :: tail ->
- let dirs = Directory.EnumerateDirectories head |> Seq.toList
- Some(Directory.EnumerateFiles head, List.append dirs tail)
- Seq.unfold generator [dir] |> Seq.concat
- let getAllFiles =
- let generator dirs = if Seq.isEmpty dirs then None
- else Some(dirs, Seq.collect Directory.EnumerateDirectories dirs)
- Seq.singleton >> Seq.unfold generator >> Seq.concat >> Seq.collect Directory.EnumerateFiles
C#
- public static IEnumerable<string> GetAllFiles(string dir) {
- return Directory.EnumerateFiles(dir).Concat(
- Directory.EnumerateDirectories(dir).SelectMany(GetAllFiles));
- }
- public static IEnumerable<FileInfo> GetAllFiles(DirectoryInfo dir) {
- return dir.GetFiles().Concat(
- from subDir in dir.GetDirectories()
- from file in GetAllFiles(subDir)
- select file
- );
- }
C++
- #include <dirent.h>
- #include <sstream>
- #include <vector>
- vector<string> get_all_files(const string& path) {
- vector<string> files;
- if (DIR* dir = opendir(path.c_str())) {
- while (struct dirent* ent = readdir(dir)) {
- string name = ent->d_name;
- if (name == "." || name == "..") {
- continue;
- }
- stringstream ss;
- ss << path << '/' << name;
- files.push_back(ss.str());
- if (ent->d_type == DT_DIR) {
- vector<string> sub_files = get_all_files(ss.str());
- for (vector<string>::iterator it = sub_files.begin(); it != sub_files.end(); it++) {
- files.push_back(*it);
- }
- }
- }
- closedir(dir);
- }
- return files;
- }
Boost を使った場合
- #include <vector>
- #include <boost/filesystem/operations.hpp>
- vector<string> get_all_files(const path& dir_path) {
- vector<string> files;
- recursive_directory_iterator end;
- for (recursive_directory_iterator it(dir_path); it != end; it++) {
- files.push_back(it->path().string());
- }
- return files;
- }
Go
- func GetAllFiles(dir string) (*list.List, error) {
- info, err := os.Stat(dir)
- if err != nil { return nil, err }
- if info.IsDir() {
- files, err := ioutil.ReadDir(dir)
- if err != nil { return nil, err }
- list1 := list.New()
- for _, file := range files {
- subdir := fmt.Sprintf("%s/%s", dir, file.Name())
- list1.PushBack(subdir)
- list2, err := GetAllFiles(subdir)
- if err != nil { return nil, err }
- list1.PushBackList(list2)
- }
- return list1, nil
- }
- return list.New(), nil
- }
Rust
- pub fn get_all_files(path: &path::Path, files: &mut Vec<String>) {
- let entries = fs::read_dir(path).unwrap();
- for entry in entries {
- let e = entry.unwrap();
- let file_type = e.file_type().unwrap();
- if file_type.is_dir() {
- get_all_files(&e.path(), files);
- } else {
- files.push(format!("{}", e.path().display()));
- }
- }
- }
TypeScript
- function getAllFiles(dir: string): string[] {
- return fs.readdirSync(dir).flatMap(file => {
- let path = `${dir}/${file}`;
- return fs.statSync(path).isDirectory() ? getAllFiles(path) : path;
- });
- }
JavaScript
Node.js の場合
- function getAllFiles(dir) {
- return fs.readdirSync(dir).flatMap(file => {
- let path = `${dir}/${file}`;
- return fs.statSync(path).isDirectory() ? getAllFiles(path) : path;
- });
- }
CoffeeScript
Node.js の場合
- getAllFiles = (dir) ->
- fs.readdirSync(dir).flatMap (file) ->
- path = "#{dir}/#{file}"
- if fs.statSync(path).isDirectory() then getAllFiles path else path
Ruby
- def get_all_files(dir)
- test('d', dir) ? Dir.glob(dir + '/*').flat_map {|d| get_all_files d } : [dir]
- end
Python
- def get_all_files(dir):
- l = []
- for dirpath, dirnames, filenames in os.walk(dir):
- l.extend(dirpath + '/' + f for f in filenames)
- return l
- def get_all_files(dir):
- l = []
- if os.path.isdir(dir):
- for f in glob.glob(dir + '/*'):
- l.extend(get_all_files(f))
- else:
- l.append(dir)
- return l
- def get_all_files(dir):
- return (f for f in pathlib.Path(dir).glob('**/*') if f.is_file())
PHP
- function get_all_files($dir, array &$files = NULL) {
- if ($files === NULL) {
- $files = [];
- }
- if (($files_in_dir = scandir($dir)) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message'] . "; $dir");
- }
- foreach ($files_in_dir as $file) {
- if ($file !== '.' && $file !== '..') {
- $file_path = "$dir/$file";
- array_push($files, $file_path);
- if (is_dir($file_path)) {
- get_all_files($file_path, $files);
- }
- }
- }
- return $files;
- }
Perl
- sub get_all_files {
- my $dir = shift;
- my @result;
- find sub { push @result, $File::Find::name }, $dir;
- @result;
- }
Java
1行ずつ読み書き
- try (Stream<String> lines = Files.lines(Path.of("in.txt"));
- BufferedWriter writer = Files.newBufferedWriter(Path.of("out.txt"))) {
- int lineNumber = 0;
- Iterable<String> iter = lines::iterator;
- for (String line : iter) {
- writer.write(++lineNumber + " " + line);
- writer.newLine();
- }
- }
先に全部読む
- List<String> lines = Files.readAllLines(Path.of("in.txt"));
- try (BufferedWriter writer = Files.newBufferedWriter(Path.of("out.txt"))) {
- int lineNumber = 0;
- for (String line : lines) {
- writer.write(++lineNumber + " " + line);
- writer.newLine();
- }
- }
Groovy
1行ずつ読み書き
- new File('in.txt').withReader { reader ->
- new File('out.txt').withWriter { writer ->
- def lineNumber = 0
- reader.eachLine { line -> writer.writeLine(++lineNumber + ' ' + line) }
- }
- }
先に全部読む
- def lines = new File('in.txt').readLines()
- new File('out.txt').withWriter { writer ->
- lines.eachWithIndex { line, i -> writer.writeLine((i + 1) + ' ' + line) }
- }
Kotlin
1行ずつ読み書き
- Files.lines(Path.of("in.txt")).use { lines ->
- Files.newBufferedWriter(Path.of("out.txt")).use { writer ->
- var lineNumber = 0
- for (line in lines) {
- writer.write("${++lineNumber} $line")
- writer.newLine()
- }
- }
- }
- File("out.txt").bufferedWriter().use { writer ->
- var lineNumber = 0
- File("in.txt").forEachLine { line ->
- writer.write("${++lineNumber} $line")
- writer.newLine()
- }
- }
- File("in.txt").bufferedReader().use { reader ->
- File("out.txt").bufferedWriter().use { writer ->
- for ((i, line) in reader.lineSequence().withIndex()) {
- writer.write("${i + 1} $line")
- writer.newLine()
- }
- }
- }
先に全部読む
- val lines = File("in.txt").readLines()
- File("out.txt").bufferedWriter().use { writer ->
- for ((i, line) in lines.withIndex()) {
- writer.write("${i + 1} $line")
- writer.newLine()
- }
- }
Scala
Scala 2.13以降
1行ずつ読み書き
- Using(Source fromFile "in.txt") { src =>
- Using(Files newBufferedWriter Path.of("out.txt")) { writer =>
- for ((line, i) <- src.getLines().zipWithIndex) writer.write("%d %s%n".format(i + 1, line))
- }.get
- }.get
- Using.Manager { use =>
- val src = use(Source fromFile "in.txt")
- val writer = use(Files newBufferedWriter Path.of("out.txt"))
- for ((line, i) <- src.getLines().zipWithIndex) writer.write("%d %s%n".format(i + 1, line))
- }.get
scala-io を使った場合
1行ずつ読み書き
- implicit val codec = Codec.UTF8
- val inLines = Path("in.txt").lines(Terminators.Auto, true)
- val outlines = for ((line, i) <- inLines.zipWithIndex) yield "%d %s".format(i + 1, line)
- Path("out.txt").writeStrings(outlines)
- implicit val codec = Codec.UTF8
- val inLines = new FileInputStream("in.txt").asInput.lines(Terminators.Auto, true)
- Path("out.txt").openOutput { out =>
- for ((line, i) <- inLines.zipWithIndex) out.write("%d %s".format(i + 1, line))
- }
Erlang
1行ずつ読み書き
- fold_lines(File, Fun, AccIn) ->
- case io:get_line(File, "") of
- eof -> AccIn;
- Line -> fold_lines(File, Fun, Fun(Line, AccIn))
- end.
- {ok, In} = file:open("in.txt", read),
- try
- {ok, Out} = file:open("out.txt", write),
- try
- fold_lines(In, fun(Line, LineNumber) ->
- io:format(Out, "~b ~s", [LineNumber, Line]),
- LineNumber + 1
- end, 1)
- after
- file:close(Out)
- end
- after
- file:close(In)
- end.
Haskell
1行ずつ読み書き
- bracket (openFile "in.txt" ReadMode) hClose
- $ \ inHandle -> do
- bracket (openFile "out.txt" WriteMode) hClose
- $ \ outHandle -> do
- let readWrite lineNumber = IO.catch
- (do line <- hGetLine inHandle
- hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
- readWrite $ lineNumber + 1)
- (\ e -> if isEOFError e then return () else ioError e)
- readWrite 1
- inHandle <- openFile "in.txt" ReadMode
- finally
- (do outHandle <- openFile "out.txt" WriteMode
- finally
- (do let readWrite lineNumber = IO.catch
- (do line <- hGetLine inHandle
- hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
- readWrite $ lineNumber + 1)
- (\ e -> if isEOFError e then return () else ioError e)
- readWrite 1)
- (hClose outHandle))
- (hClose inHandle)
先に全部読む
- contents <- readFile "in.txt"
- writeFile "out.txt" $ unlines $ map f $ zip [1..] $ lines contents where
- f (lineNumber, line) = (show lineNumber) ++ " " ++ line
- contents <- readFile "in.txt"
- bracket (openFile "out.txt" WriteMode) hClose
- $ \ outHandle -> do
- let write (lineNumber, line) = hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
- mapM_ write $ zip [1..] $ lines contents
- contents <- readFile "in.txt"
- outHandle <- openFile "out.txt" WriteMode
- finally
- (do let write (lineNumber, line) = hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
- mapM_ write $ zip [1..] $ lines contents)
- (hClose outHandle)
Cabal の
MissingH を使った場合
先に全部読む
- bracket (openFile "in.txt" ReadMode) hClose
- $ \ inHandle -> do
- bracket (openFile "out.txt" WriteMode) hClose
- $ \ outHandle -> do
- lines <- hGetLines inHandle
- let f (lineNumber, line) = (show lineNumber) ++ " " ++ line
- hPutStrLns outHandle $ map f $ zip [1..] lines
- inHandle <- openFile "in.txt" ReadMode
- finally
- (do outHandle <- openFile "out.txt" WriteMode
- finally
- (do lines <- hGetLines inHandle
- let f (lineNumber, line) = (show lineNumber) ++ " " ++ line
- hPutStrLns outHandle $ map f $ zip [1..] lines)
- (hClose outHandle))
- (hClose inHandle)
PowerShell
- cat in.txt | foreach -Begin { $lineNumber = 0 } { "$(++$lineNumber + 0) $_" } > out.txt
- cat in.txt | foreach -Begin { $lineNumber = 0 } { '' + (++$lineNumber) + ' ' + $_ } > out.txt
- cat in.txt | foreach -Begin { $lineNumber = 0 } { '{0} {1}' -f ++$lineNumber, $_ } > out.txt
F#
1行ずつ読み書き
- use reader = new StreamReader "in.txt"
- use writer = new StreamWriter "out.txt"
- let lines = seq { while not reader.EndOfStream do yield reader.ReadLine() }
- lines |> Seq.iteri (fun i line -> fprintfn writer "%d %s" (i + 1) line)
- use reader = new StreamReader "in.txt"
- use writer = new StreamWriter "out.txt"
- let lines = Seq.unfold <| fun (reader : StreamReader) ->
- match reader.ReadLine() with
- | null -> None
- | line -> Some(line, reader)
- lines reader |> Seq.iteri (fun i line -> fprintfn writer "%d %s" (i + 1) line)
- use reader = new StreamReader "in.txt"
- use writer = new StreamWriter "out.txt"
- let mutable lineNumber = 0
- while not reader.EndOfStream do
- lineNumber <- lineNumber + 1
- fprintfn writer "%d %s" lineNumber <| reader.ReadLine()
- use reader = new StreamReader "in.txt"
- use writer = new StreamWriter "out.txt"
- let generator lineNumber =
- match reader.ReadLine() with
- | null -> None
- | line -> Some(sprintf "%d %s" lineNumber line, lineNumber + 1)
- Seq.unfold generator 1 |> Seq.iter writer.WriteLine
- use reader = new StreamReader "in.txt"
- use writer = new StreamWriter "out.txt"
- let rec readWrite lineNumber =
- match reader.ReadLine() with
- | null -> ()
- | line ->
- fprintfn writer "%d %s" lineNumber line
- readWrite <| lineNumber + 1
- readWrite 1
C#
1行ずつ読み書き
- using (StreamReader reader = new StreamReader("in.txt")) {
- using (StreamWriter writer = new StreamWriter("out.txt")) {
- int lineNumber = 0;
- string line;
- while ((line = reader.ReadLine()) != null) {
- writer.WriteLine(++lineNumber + " " + line);
- }
- }
- }
1行ずつ読み書き
C# 8.0以降
- using var reader = new StreamReader("in.txt");
- using var writer = new StreamWriter("out.txt");
- int lineNumber = 0;
- string line;
- while ((line = reader.ReadLine()) != null) {
- writer.WriteLine(++lineNumber + " " + line);
- }
C++
1行ずつ読み書き
- #include <fstream>
- ifstream in("in.txt");
- if (! in) {
- return "cannot open in.txt";
- }
- ofstream out("out.txt");
- if (! out) {
- return "cannot open out.txt";
- }
- const int BUF_SIZE = 1024;
- char buf[BUF_SIZE];
- int line_number = 0;
- while (! in.eof()) {
- in.getline(buf, BUF_SIZE);
- if (in.gcount()) {
- out << ++line_number << " " << buf << endl;
- }
- }
Go
1行ずつ読み書き
- lineNumber := 0
- inFile, err := os.Open("in.txt")
- if err != nil { return err }
- defer inFile.Close()
- outFile, err := os.OpenFile("out.txt", os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
- if err != nil { return err }
- defer outFile.Close()
- reader := bufio.NewReader(inFile)
- for {
- line, err := reader.ReadString('\n')
- if err == io.EOF { break }
- if err != nil { return err }
- lineNumber++
- _, err = fmt.Fprintf(outFile, "%d %s", lineNumber, line)
- if err != nil { return err }
- }
Rust
- let reader = BufReader::new(fs::File::open("in.txt").unwrap());
- let mut writer = BufWriter::new(fs::File::create("out.txt").unwrap());
- let mut index = 0;
- for line in reader.lines() {
- index += 1;
- write!(writer, "{index} {}\n", line.unwrap()).unwrap();
- }
TypeScript
Node.js の場合
1行ずつ読み書き
- let input = fs.createReadStream('in.txt', 'utf8');
- try {
- let output = fs.createWriteStream('out.txt', 'utf8');
- try {
- await new Promise(resolve => {
- let i = 0;
- let reader = readline.createInterface({ input });
- reader.on('line', line => output.write(`${++i} ${line}\n`));
- reader.on('close', resolve);
- });
- } finally {
- output.close();
- }
- } finally {
- input.close();
- }
Node.js の場合
先に全部読む
- let content = await util.promisify(fs.readFile)('in.txt', 'utf8');
- let lines = content.split(/\n/);
- if (lines[lines.length - 1] === '') {
- lines.pop();
- }
- let output = fs.createWriteStream('out.txt', 'utf8');
- try {
- for (let i = 0; i < lines.length; i++) {
- output.write(`${i + 1} ${lines[i]}\n`);
- }
- } finally {
- output.close();
- }
JavaScript
Node.js の場合
1行ずつ読み書き
- let input = fs.createReadStream('in.txt', 'utf8');
- try {
- let output = fs.createWriteStream('out.txt', 'utf8');
- try {
- await new Promise(resolve => {
- let i = 0;
- let reader = readline.createInterface({ input });
- reader.on('line', line => output.write(`${++i} ${line}\n`));
- reader.on('close', resolve);
- });
- } finally {
- output.close();
- }
- } finally {
- input.close();
- }
Node.js の場合
先に全部読む
- let content = await util.promisify(fs.readFile)('in.txt', 'utf8');
- let lines = content.split(/\n/);
- if (lines[lines.length - 1] === '') {
- lines.pop();
- }
- let output = fs.createWriteStream('out.txt', 'utf8');
- try {
- for (let i = 0; i < lines.length; i++) {
- output.write(`${i + 1} ${lines[i]}\n`);
- }
- } finally {
- output.close();
- }
CoffeeScript
Node.js の場合
1行ずつ読み書き
- input = fs.createReadStream 'in.txt', 'utf8'
- try
- output = fs.createWriteStream 'out.txt', 'utf8'
- try
- await new Promise (resolve) ->
- i = 0
- reader = readline.createInterface { input }
- reader.on 'line', (line) -> output.write "#{++i} #{line}\n"
- reader.on 'close', resolve
- finally
- output.close()
- finally
- input.close()
Node.js の場合
先に全部読む
- content = await util.promisify(fs.readFile) 'in.txt', 'utf8'
- lines = content.split /\n/
- lines.pop() if lines[lines.length - 1] == ''
- output = fs.createWriteStream 'out.txt', 'utf8'
- try
- output.write "#{i + 1} #{lines[i]}\n" for i in [0...lines.length]
- finally
- output.close()
Ruby
1行ずつ読み書き
- open 'in.txt', 'r' do |in_file|
- open 'out.txt', 'w' do |out_file|
- in_file.each {|line| out_file << in_file.lineno << ' ' << line }
- end
- end
- open 'out.txt', 'w' do |out_file|
- lineno = 0
- File.foreach 'in.txt' do |line|
- lineno += 1
- out_file << lineno << ' ' << line
- end
- end
先に全部読む
- lines = IO.readlines 'in.txt'
- open 'out.txt', 'w' do |out_file|
- lines.each_with_index {|line, i| out_file << (i + 1) << ' ' << line }
- end
Python
1行ずつ読み書き
- with open('in.txt', 'r') as in_file:
- with open('out.txt', 'w') as out_file:
- for i, line in enumerate(in_file):
- out_file.write('%d %s' % (i + 1, line))
- with open('in.txt', 'r') as in_file:
- with open('out.txt', 'w') as out_file:
- for i, line in enumerate(in_file):
- out_file.write(str(i + 1) + ' ' + line)
- with open('in.txt', 'r') as in_file:
- with open('out.txt', 'w') as out_file:
- for i, line in enumerate(in_file):
- print(i + 1, line, end = '', file = out_file)
- in_file = fileinput.input('in.txt')
- try:
- with open('out.txt', 'w') as out_file:
- for line in in_file:
- out_file.write('%d %s' % (in_file.lineno(), line))
- finally:
- in_file.close()
- with contextlib.closing(fileinput.input('in.txt')) as in_file:
- with open('out.txt', 'w') as out_file:
- for line in in_file:
- out_file.write('%d %s' % (in_file.lineno(), line))
先に全部読む
- with open('in.txt', 'r') as in_file:
- lines = in_file.readlines()
- with open('out.txt', 'w') as out_file:
- for i, line in enumerate(lines):
- out_file.write(str(i + 1) + ' ' + line)
- with open('in.txt', 'r') as in_file:
- lines = in_file.readlines()
- with open('out.txt', 'w') as out_file:
- for i, line in enumerate(lines):
- print(i + 1, line, end = '', file = out_file)
PHP
先に全部読む
- if (($lines = file('in.txt')) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
- foreach ($lines as $i => &$line) {
- $line = ($i + 1) . ' ' . $line;
- }
- if (file_put_contents('out.txt', $lines) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
Perl
Perl 5.6以降での基本形
1行ずつ読み書き
- open my $in, 'in.txt' or die "Cannot open in.txt; $!";
- open my $out, '> out.txt' or die "Cannot open out.txt; $!";
- print $out "$. $_" while <$in>;
- open my $in, '<', 'in.txt' or die "Cannot open in.txt; $!";
- open my $out, '>', 'out.txt' or die "Cannot open out.txt; $!";
- printf {$out} '%d %s', $., $_ while <$in>;
先に全部読む
- open my $in, 'in.txt' or die "Cannot open in.txt; $!";
- open my $out, '> out.txt' or die "Cannot open out.txt; $!";
- my @lines = <$in>;
- printf $out '%d %s', $_ + 1, $lines[$_] for 0..$#lines;
オブジェクト指向での書き方
1行ずつ読み書き
- my $in = IO::File->new('in.txt', 'r') or die "Cannot open in.txt; $!";
- my $out = IO::File->new('out.txt', 'w') or die "Cannot open out.txt; $!";
- $out->print($in->input_line_number, " $_") while <$in>;
- my $in = IO::File->new('in.txt', O_RDONLY) or die "Cannot open in.txt; $!";
- my $out = IO::File->new('out.txt', O_WRONLY | O_CREAT) or die "Cannot open out.txt; $!";
- $out->printf('%d %s', $in->input_line_number, $_) while defined($_ = $in->getline);
先に全部読む
- my $in = IO::File->new('in.txt', 'r') or die "Cannot open in.txt; $!";
- my $out = IO::File->new('out.txt', 'w') or die "Cannot open out.txt; $!";
- my @lines = $in->getlines;
- $out->printf('%d %s', $_ + 1, $lines[$_]) for 0..$#lines;
Java
Commons Text を使った場合
- List<List<String>> rows;
- StrTokenizer tokenizer = StringTokenizer.getCSVInstance();
- try (Stream<String> lines = Files.lines(Path.of("in.csv"))) {
- rows = lines.map(line -> tokenizer.reset(line).getTokenList()).collect(Collectors.toList());
- }
- Collections.sort(rows, Comparator.comparing(row -> Double.parseDouble(row.get(0))));
- try (BufferedWriter writer = new BufferedWriter(new FileWriter("out.csv"))) {
- for (List<String> row : rows) {
- writer.write(row.stream().map(StringEscapeUtils::escapeCsv).collect(Collectors.joining(",")));
- writer.newLine();
- }
- }
opencsv を使った場合
- List<String[]> rows;
- try (CSVReader reader = new CSVReader(new FileReader("in.csv"))) {
- rows = reader.readAll();
- }
- Collections.sort(rows, Comparator.comparing(row -> Double.parseDouble(row[0])));
- try (CSVWriter writer = new CSVWriter(new FileWriter("out.csv"))) {
- writer.writeAll(rows);
- }
Groovy
Commons Text を使った場合
- def tokenizer = StringTokenizer.CSVInstance
- def tokenize = { tokenizer.reset(it).toList() }
- def rows = new File('in.csv').readLines().collect { tokenize it }
- rows = rows.sort { it[0] as double }
- new File('out.csv').withWriter { writer ->
- for (row in rows) {
- row = row.collect(StringEscapeUtils.&escapeCsv)
- writer.writeLine row.join(',')
- }
- }
opencsv を使った場合
- def rows = new File('in.csv').withReader { new CSVReader(it).readAll() }
- rows = rows.sort { it[0] as double }
- new File('out.csv').withWriter { new CSVWriter(it).writeAll rows }
Kotlin
Commons Text を使った場合
- val tokenizer = StringTokenizer.getCSVInstance()
- val lines = File("in.csv").readLines()
- val rows = lines.map { tokenizer.reset(it).getTokenList() }
- File("out.csv").bufferedWriter().use { writer ->
- for (row in rows.sortedBy { it[0].toBigDecimal() }) {
- writer.write(row.map(StringEscapeUtils::escapeCsv).joinToString(","))
- writer.newLine()
- }
- }
opencsv を使った場合
- val rows = CSVReader(FileReader("in.csv")).use { it.readAll() }
- CSVWriter(FileWriter("out.csv")).use {
- it.writeAll(rows.sortedBy { it[0].toBigDecimal() })
- }
Scala
Scala 2.13以降
Commons Text を使った場合
- val tokenizer = StringTokenizer.getCSVInstance
- def tokenize(s: String) = asScala(tokenizer reset s).toList
- val rows = Using(Source fromFile "in.csv") { _.getLines().map(tokenize).toList }.get
- Using(new BufferedWriter(new FileWriter("out.csv"))) { writer =>
- for (row <- rows.sortBy(_(0).toDouble)) {
- writer.write(row.map(StringEscapeUtils.escapeCsv) mkString ",")
- writer.newLine
- }
- }.get
Scala 2.13以降
opencsv を使った場合
- val rows = Using(new CSVReader(new FileReader("in.csv"))) { reader => asScala(reader.readAll) }.get
- Using(new CSVWriter(new FileWriter("out.csv"))) { writer =>
- rows.sortBy(_(0).toDouble).foreach(writer.writeNext _)
- }.get
Haskell
Cabal の
csv を使った場合
- Right table <- parseCSVFromFile "in.csv"
- let table' = sortBy (\ rec1 rec2 -> compare (f rec1) (f rec2)) table where
- f (cell0 : _) = case cell0 of
- '-' : s -> - (strToFloat s)
- s -> strToFloat s
- strToFloat s = case readFloat s of
- [(float, "")] -> float
- writeFile "out.csv" $ printCSV table'
PowerShell
- cat in.csv | ConvertFrom-CSV -Header @(1..9) | sort { [double] $_.'1' } | ConvertTo-CSV | select -Index @(2..9999) > out.csv
F#
- let read() =
- use parser = new TextFieldParser("in.csv", Delimiters = [|","|])
- [while not parser.EndOfData do yield parser.ReadFields()]
- let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
- let rowToString = Seq.map quote >> String.concat ","
- let write (lines : seq<string>) =
- use writer = new StreamWriter "out.csv"
- lines |> Seq.iter writer.WriteLine
- read() |> List.sortBy (fun row -> double row.[0]) |> Seq.map rowToString |> write
- let rows = using (new TextFieldParser("in.csv", Delimiters = [|","|]))
- (fun parser -> [while not parser.EndOfData do yield parser.ReadFields()])
- let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
- let rowToString = Seq.map quote >> String.concat ","
- let lines = rows |> List.sortBy (fun row -> double row.[0]) |> Seq.map rowToString
- using (new StreamWriter "out.csv")
- (fun writer -> lines |> Seq.iter writer.WriteLine)
- let rows = using (new TextFieldParser("in.csv", Delimiters = [|","|]))
- (fun parser -> [while not parser.EndOfData do yield parser.ReadFields()])
- let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
- using (new StreamWriter "out.csv")
- (fun writer ->
- for row in rows |> List.sortBy (fun row -> double row.[0]) do
- row |> Seq.map quote |> String.concat "," |> writer.WriteLine
- )
CSV I/Oライブラリ.NET を使った場合
- let rows = using (new CsvReader(new StreamReader "in.csv"))
- (fun reader ->
- let getRow() = Array.init reader.FieldCount (fun i -> reader.[i])
- [while reader.Read() do yield getRow()]
- )
- using (new CsvWriter(new StreamWriter "out.csv"))
- (fun writer ->
- for row in rows |> List.sortBy (fun row -> double row.[0]) do
- writer.Write row
- writer.WriteNewLine()
- )
C#
- var rows = new List<string[]>();
- using (var parser = new TextFieldParser("in.csv")) {
- parser.Delimiters = new string[] { "," };
- while (! parser.EndOfData) {
- rows.Add(parser.ReadFields());
- }
- }
- Func<string, string> quote = (s) => '"' + s.Replace("\"", "\"\"") + '"';
- Func<string[], string> rowToString = (row) => row.Select(quote).Aggregate((x, y) => x + ',' + y);
- var lines = from row in rows orderby double.Parse(row[0]) select rowToString(row);
- using (var writer = new StreamWriter("out.csv")) {
- foreach (var line in lines) {
- writer.WriteLine(line);
- }
- }
CSV I/Oライブラリ.NET を使った場合
- var rows = new List<string[]>();
- using (var reader = new CsvReader(new StreamReader("in.csv"))) {
- while (reader.Read()) {
- var row = new string[reader.FieldCount];
- for (var i = 0; i < row.Length; i++) {
- row[i] = reader[i];
- }
- rows.Add(row);
- }
- }
- using (var writer = new CsvWriter(new StreamWriter("out.csv"))) {
- foreach (var row in rows.OrderBy(row => double.Parse(row[0]))) {
- writer.Write(row);
- writer.WriteNewLine();
- }
- }
Go
- type FirstNumAscending [][]string
- func (this FirstNumAscending) Len() int {
- return len(this)
- }
- func (this FirstNumAscending) Less(i, j int) bool {
- ni, _ := strconv.Atoi(this[i][0])
- nj, _ := strconv.Atoi(this[j][0])
- return ni < nj
- }
- func (this FirstNumAscending) Swap(i, j int) {
- this[i], this[j] = this[j], this[i]
- }
- inFile, err := os.Open("in.csv")
- if err != nil { return err }
- defer inFile.Close()
- reader := csv.NewReader(inFile)
- rows, err := reader.ReadAll()
- if err != nil { return err }
- sort.Sort(FirstNumAscending(rows))
- outFile, err := os.OpenFile("out.csv", os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
- if err != nil { return err }
- defer outFile.Close()
- writer := csv.NewWriter(outFile)
- writer.WriteAll(rows)
Rust
csv を使った場合
- let mut reader = csv::ReaderBuilder::new().has_headers(false).from_path("in.csv").unwrap();
- let mut writer = csv::Writer::from_path("out.csv").unwrap();
- let it = reader.records().map(|r| {
- let record = r.unwrap();
- let n: i32 = record[0].parse().unwrap();
- (n, record)
- });
- let mut vec: Vec<_> = it.collect();
- vec.sort_by_key(|&(n, _)| n);
- for (_, record) in vec {
- writer.write_record(record.iter()).unwrap();
- }
Ruby
- rows = CSV.readlines('in.csv', :converters => :numeric).sort_by {|row| row[0] }
- CSV.open 'out.csv', 'w' do |writer|
- rows.each {|row| writer << row }
- end
Python
- with open('in.csv', 'r') as f:
- rows = list(csv.reader(f))
- rows.sort(key = lambda row: float(row[0]))
- with open('out.csv', 'w') as f:
- csv.writer(f, lineterminator = '\n').writerows(rows)
PHP
- if (($f = fopen('in.csv', 'r')) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
- $rows = [];
- while (($row = fgetcsv($f)) !== FALSE) {
- array_push($rows, $row);
- }
- fclose($f);
- usort($rows, function($a, $b) { return (float)$a[0] - (float)$b[0]; });
- if (($f = fopen('out.csv', 'w')) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
- foreach ($rows as $row) {
- if (fputcsv($f, $row) === FALSE) {
- $error = error_get_last();
- fclose($f);
- throw new Exception($error['message'] . '; out.csv');
- }
- }
- fclose($f);
Perl
CPAN の
Text::CSV を使った場合
- open my $in, 'in.csv' or die "Cannot open in.csv; $!";
- open my $out, '> out.csv' or die "Cannot open out.csv; $!";
- my $csv = Text::CSV->new;
- my @rows;
- push @rows, $_ while $_ = $csv->getline($in);
- $csv->eol($/);
- $csv->print($out, $_) for sort { $a->[0] <=> $b->[0] } @rows;
Groovy
- class CsvParser {
- private def sb
- private def lastMatch
- def CsvParser(input) {
- sb = new StringBuilder(input)
- }
- private def parse(regex) {
- lastMatch = sb =~ "^(?:$regex)"
- if (lastMatch.find()) {
- def result = lastMatch.group()
- sb.delete 0, result.length()
- result
- }
- }
- private def parseList(separator, closure) {
- def result = []
- for (;;) {
- result << closure()
- if (! parse(separator)) break
- }
- result
- }
- private def parseCell() {
- if (parse('"((""|[^"])*)"')) {
- lastMatch.group(1).replace '""', '"'
- } else {
- parse '[^",\r\n]*'
- }
- }
- def parseRow() {
- parseList ',', this.&parseCell
- }
- def parseTable() {
- parseList '\r\n?|\n', this.&parseRow
- }
- }
- def csv = new File('in.csv').withReader { it.text }
- def table = new CsvParser(csv).parseTable()
Scala
- class CsvParser extends RegexParsers {
- override def skipWhitespace = false
- private val q = "\""
- private val ln = """\r\n?|\n""".r
- private val quotedCell = q ~> """([^"]|"")*""".r <~ q ^^ { _.replace(q + q, q) }
- private val nonQuotedCell = """[^",\r\n]*""".r
- private val cell = quotedCell | nonQuotedCell
- private val row = repsep(cell, ",")
- private val table = repsep(row, ln)
- def parseRow (in: CharSequence) = parseAll(row, in)
- def parseTable(in: CharSequence) = parseAll(table, in)
- }
- val src = Source fromFile "in.csv"
- val csv = try src.mkString finally src.close
- val table = new CsvParser parseTable csv get
Erlang
- parse(Input, Items) ->
- case Items of
- [H|T] ->
- HasPrefix = lists:prefix(H, Input),
- if
- HasPrefix -> {H, lists:nthtail(length(H), Input)};
- true -> parse(Input, T)
- end;
- [] -> {[], Input}
- end.
- parse_list(List, Input, Fun, Separators) ->
- {Item, Input2} = Fun(Input),
- case parse(Input2, Separators) of
- {[], Input3} -> {lists:reverse([Item|List]), Input3};
- {_, Input3} -> parse_list([Item|List], Input3, Fun, Separators)
- end.
- parse_table(Input) -> parse_list([], Input, fun parse_row/1, ["\r\n", "\r", "\n"]).
- parse_row(Input) -> parse_list([], Input, fun parse_cell/1, [","]).
- parse_cell([$"|T]) -> parse_quoted_cell([], T);
- parse_cell(Input) -> parse_non_quoted_cell([], Input).
- parse_quoted_cell(S, [$", $"|T]) -> parse_quoted_cell([$"|S], T);
- parse_quoted_cell(S, [$"|T]) -> {lists:reverse(S), T};
- parse_quoted_cell(S, [H|T]) -> parse_quoted_cell([H|S], T).
- parse_non_quoted_cell(S, [H|T]) ->
- IsMember = lists:member(H, [$,, $", $\r, $\n]),
- if
- IsMember -> {lists:reverse(S), [H|T]};
- true -> parse_non_quoted_cell([H|S], T)
- end;
- parse_non_quoted_cell(S, []) -> {lists:reverse(S), []}.
- {ok, Bin} = file:read_file("in.csv"),
- Input = binary_to_list(Bin),
- {Result, []} = parse_table(Input).
Haskell
- quotedCell = do
- char '"'
- contents <- many $ string "\"\"" +++ munch1 (/= '"')
- char '"'
- return $ concat $ map unescape contents
- where unescape "\"\"" = "\""
- unescape s = s
- nonQuotedCell = munch (\ c -> notElem c "\",\r\n")
- cell = quotedCell +++ nonQuotedCell
- row = cell `sepBy` char ','
- table = row `sepBy` (string "\r" +++ string "\n" +++ string "\r\n")
- parse parser = fst . head . readP_to_S (do p <- parser; eof; return p)
- contents <- readFile "in.csv"
- let table' = parse table contents
Cabal の
MissingH、
parsec を使った場合
- quotedCell = do
- segments <- many1
- (do char '"'
- content <- option "" $ many1 $ noneOf "\""
- char '"'
- return content)
- return $ join "\"" segments
- nonQuotedCell = option "" $ many1 $ noneOf "\",\r\n"
- cell = quotedCell <|> nonQuotedCell
- row = cell `sepBy` char ','
- table = row `sepBy` (string "\r" <|> string "\n" <|> string "\r\n")
- parse' parser = forceEither . parse (do p <- parser; eof; return p) ""
- contents <- readFile "in.csv"
- let table' = parse' table contents
F#
- type CsvParser(input : string) =
- let sb = new StringBuilder(input)
- let parse pattern =
- let m = Regex.Match(string sb, sprintf "^(?:%s)" pattern)
- match m.Success with
- | true -> sb.Remove(0, m.Value.Length) |> ignore
- Some m
- | false -> None
- let (|Parse|_|) pattern _ = parse pattern
- let parseList separator (parseItem : unit -> Option<'a>) =
- Some [
- let _continue = ref true
- while !_continue do
- match parseItem() with
- | Some a -> yield a
- | None -> ()
- match parse separator with
- | Some _ -> ()
- | None -> _continue := false
- ]
- let parseCell() =
- match () with
- | Parse @"""((""""|[^""])*)""" m -> Some(m.Groups.[1].Value.Replace(@"""""", @""""))
- | Parse @"[^"",\r\n]*" m -> Some m.Value
- | _ -> None
- member this.ParseRow() = parseList "," parseCell
- member this.ParseTable() = parseList @"\r\n?|\n" this.ParseRow
- let csv = using (new StreamReader("in.csv")) (fun reader -> reader.ReadToEnd())
- let table = (new CsvParser(csv)).ParseTable().Value
Ruby
- class CsvParser
- def initialize input
- @ss = StringScanner.new input
- end
- def parse_cell
- case
- when @ss.scan(/"(([^"]|"")*)"/) ; @ss[1].gsub(/""/, '"')
- when @ss.scan(/[^",\r\n]*/) ; @ss[0]
- end
- end
- def parse_row
- parse_list(/,/) { parse_cell }
- end
- def parse_table
- parse_list(/\r\n?|\n/) { parse_row }
- end
- private
- def parse_list separator, &block
- result = []
- begin result << block.call end while @ss.scan separator
- result
- end
- end
- table = open 'in.csv' do |file|
- CsvParser.new(file.read).parse_table
- end
rparsec を使った場合
- class CsvParser
- extend RParsec::Parsers
- extend RParsec::Functors
- QUOTED_CELL = (
- char('"') >> (not_char('"') | str('""')).many_.fragment << char('"')
- ).map {|s| s.gsub /""/, '"' }
- NON_QUOTED_CELL = not_among('"', ',', "\r", "\n").many_.fragment
- CELL = QUOTED_CELL | NON_QUOTED_CELL
- ROW = CELL.delimited char(',')
- TABLE = ROW.delimited(str("\r\n") | str("\r") | str("\n"))
- end
- table = CsvParser::TABLE.parse(File.read 'in.csv')
Java
- MessageDigest md = MessageDigest.getInstance("MD5");
- try (FileInputStream stream = new FileInputStream("in.txt")) {
- byte[] bytes = new byte[1024];
- int length;
- while ((length = stream.read(bytes)) > 0) {
- md.update(bytes, 0, length);
- }
- }
- Formatter formatter = new Formatter();
- for (byte b : md.digest()) {
- formatter.format("%02x", b);
- }
- String hash = formatter.toString();
- byte[] fileBytes = Files.readAllBytes(Path.of("in.txt"));
- byte[] hashBytes = MessageDigest.getInstance("MD5").digest(fileBytes)
- Formatter formatter = new Formatter();
- for (byte b : hashBytes) {
- formatter.format("%02x", b);
- }
- String hash = formatter.toString();
Groovy
- def fileBytes = new File('in.txt').readBytes()
- def hashBytes = MessageDigest.getInstance('MD5').digest(fileBytes)
- def hash = hashBytes.collect { String.format '%02x', it }.join()
Kotlin
- val md = MessageDigest.getInstance("MD5")
- File("in.txt").forEachBlock { buf, length -> md.update(buf, 0, length) }
- val hash = md.digest().map("%02x"::format).joinToString("")
Scala
- val md = MessageDigest.getInstance("MD5")
- val stream = new FileInputStream("in.txt")
- try {
- val bytes = new Array[Byte](1024)
- var eof = false
- while (! eof) {
- val length = stream.read(bytes)
- if (length > 0) md.update(bytes, 0, length) else { eof = true }
- }
- } finally {
- stream.close
- }
- val hash = md.digest.map("%02x".format(_)).mkString
Scala 3.0以降
- val md = MessageDigest.getInstance("MD5")
- val stream = FileInputStream("in.txt")
- try
- val bytes = new Array[Byte](1024)
- var eof = false
- while ! eof do
- val length = stream.read(bytes)
- if length > 0 then md.update(bytes, 0, length) else eof = true
- finally
- stream.close
- val hash = md.digest.map("%02x".format(_)).mkString
java.io.InputStream をラップしたクラスを使った場合
- class BytesIterator(in: InputStream, bufSize: Int = 1024 * 8) extends Iterator[(Array[Byte], Int)] with Closeable {
- private val buf = new Array[Byte](bufSize)
- private var readSize = 0
- def this(file: File) = this(new FileInputStream(file))
- override def hasNext = { readSize = in.read(buf); readSize > 0 }
- override def next = (buf, readSize)
- override def close { in.close }
- }
- val md = MessageDigest.getInstance("MD5")
- val bytesIter = new BytesIterator(new File("in.txt"))
- try {
- for ((bytes, length) <- bytesIter) md.update(bytes, 0, length)
- } finally {
- bytesIter.close
- }
- val hash = md.digest.map("%02x".format(_)).mkString
Erlang
- {ok, Binary} = file:read_file("in.txt"),
- Digest = erlang:md5(Binary),
- Hash = lists:flatten([io_lib:format("~2.16.0b", [Byte]) || Byte <- binary_to_list(Digest)]).
Haskell
Cabal の
MissingH を使った場合
- contents <- readFile "in.txt"
- let hash = md5s $ Str contents
PowerShell
- $stream = New-Object System.IO.FileStream in.txt, Open
- trap { $stream.Close() }
- $provider = [System.Security.Cryptography.MD5CryptoServiceProvider]::Create()
- $hash = [string]::Join('', ($provider.ComputeHash($stream) | foreach { $_.ToString('x2') }))
- $stream.Close()
F#
- let bytes = using (new FileStream("in.txt", FileMode.Open))
- (MD5CryptoServiceProvider.Create().ComputeHash)
- let hash = [for b in bytes -> b.ToString "x2"] |> String.concat ""
C#
- using (var stream = new FileStream("in.txt", FileMode.Open)) {
- var bytes = MD5CryptoServiceProvider.Create().ComputeHash(stream);
- var hash = string.Join("", bytes.Select(b => b.ToString("x2")));
- }
Go
- var readBytes [1024]byte
- file, err := os.Open("in.txt")
- if err != nil { return err }
- defer file.Close()
- summer := md5.New()
- for {
- n, err := file.Read(readBytes[:])
- if err == io.EOF { break }
- if err != nil { return err }
- summer.Write(readBytes[:n])
- }
- hashStr := fmt.Sprintf("%0x", summer.Sum([]byte{}))
Rust
md5 を使った場合
- let mut file = fs::File::open("in.txt").unwrap();
- let mut buf = Vec::new();
- file.read_to_end(&mut buf).unwrap();
- let digest = md5::compute(buf.as_slice());
- let hash = format!("{:x}", digest);
TypeScript
Node.js の場合
- let md = crypto.createHash('md5');
- let inStream = fs.ReadStream('in.txt');
- inStream.on('data', data => md.update(data));
- inStream.on('end', () => {
- inStream.destroy();
- let hash = md.digest('hex');
- ...
- });
JavaScript
Node.js の場合
- let md = crypto.createHash('md5');
- let inStream = fs.ReadStream('in.txt');
- inStream.on('data', data => md.update(data));
- inStream.on('end', () => {
- inStream.destroy();
- let hash = md.digest('hex');
- ...
- });
CoffeeScript
Node.js の場合
- md = crypto.createHash 'md5'
- inStream = fs.ReadStream 'in.txt'
- inStream.on 'data', (data) ->
- md.update data
- inStream.on 'end', ->
- inStream.destroy()
- hash = md.digest 'hex'
Ruby
- hash = open('in.txt', 'rb') {|file| Digest::MD5.hexdigest file.read }
Python
- with open('in.txt', 'rb') as file:
- bytes = file.read()
- hash = hashlib.md5(bytes).hexdigest()
PHP
- if (($contents = file_get_contents('in.txt', FILE_BINARY)) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
- $hash = md5($contents);
Perl
一定のサイズずつ読む
- open my $in, '<:raw', 'in.txt' or die "Cannot open in.txt; $!";
- my $hash = Digest::MD5->new->addfile($in)->hexdigest;
先に全部読む
- open my $in, '<:raw', 'in.txt' or die "Cannot open in.txt; $!";
- my $hash = Digest::MD5::md5_hex <$in>;
下記のようなファイルを読み込んで、form 要素の action 属性と各 input 要素の name 属性を取得する。
- <?xml version="1.0" encoding="UTF-8"?>
- <html>
- <head>
- </head>
- <body>
- <form action="/persons/create" method="post">
- Name: <input type="text" name="name" /><br />
- Age: <input type="text" name="age" /><br />
- <input type="submit" name="submit" value="OK" />
- </form>
- </body>
- </html>
Java
先に全部読む
- DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = builder.parse(new File("in.xhtml"));
- Node form = doc.getElementsByTagName("form").item(0);
- String action = form.getAttributes().getNamedItem("action").getNodeValue();
- List<String> names = new ArrayList<String>();
- for (int i = 0; true; i++) {
- Node elem = form.getChildNodes().item(i);
- if (elem == null) break;
- if (elem.getNodeName().equals("input")) {
- names.add(elem.getAttributes().getNamedItem("name").getNodeValue());
- }
- }
- DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = builder.parse(new File("in.xhtml"));
- XPathFactory factory = XPathFactory.newInstance();
- String action = (String) factory.newXPath().compile("//form/@action").evaluate(doc, XPathConstants.STRING);
- NodeList nodes = (NodeList) factory.newXPath().compile("//input/@name").evaluate(doc, XPathConstants.NODESET);
- int length = nodes.getLength();
- List<String> names = new ArrayList<String>(length);
- for (int i = 0; i < length; i++) {
- names.add(nodes.item(i).getNodeValue());
- }
順次読み込み
- final StringBuilder action = new StringBuilder();
- final List<String> names = new ArrayList<String>();
- SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
- parser.parse(new File("in.xhtml"), new DefaultHandler() {
- @Override
- public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
- if (name.equals("form")) {
- action.append(attributes.getValue("action"));
- } else if (name.equals("input")) {
- names.add(attributes.getValue("name"));
- }
- }
- });
- final StringBuilder action = new StringBuilder();
- final List<String> names = new ArrayList<String>();
- BufferedReader reader = new BufferedReader(new FileReader("in.xhtml"));
- try {
- new ParserDelegator().parse(reader, new HTMLEditorKit.ParserCallback() {
- @Override
- public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
- if (t.equals(HTML.Tag.INPUT)) {
- names.add((String) a.getAttribute(HTML.Attribute.NAME));
- }
- }
- @Override
- public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
- if (t.equals(HTML.Tag.FORM)) {
- action.append(a.getAttribute(HTML.Attribute.ACTION));
- }
- }
- }, false);
- } finally {
- reader.close();
- }
Groovy
先に全部読む
- def doc = new XmlParser().parse('in.xhtml')
- def form = doc.body.form[0]
- def action = form.attribute('action')
- def names = form.input*.attribute('name')
- def root = new XmlSlurper().parse('in.xhtml')
- def action = root.body.form.@action
- def names = root.body.form.input*.@name
- def doc = new File('in.xhtml').withReader(DOMBuilder.&parse)
- def root = doc.documentElement
- use (DOMCategory) {
- def action = root.'*'.form.'@action'
- def names = root.'**'.input*.'@name'
- }
順次読み込み
- def action
- def names = []
- def parser = SAXParserFactory.newInstance().newSAXParser()
- parser.parse(new File('in.xhtml'), new DefaultHandler() {
- @Override void startElement(String uri, String localName, String name, Attributes attributes) {
- switch (name) {
- case 'form':
- action = attributes.getValue('action')
- break
- case 'input':
- names << attributes.getValue('name')
- break
- }
- }
- })
Scala
先に全部読む
- val doc = XML.loadFile("in.xhtml")
- val action = doc \\ "form" \ "@action" text
- val names = doc \\ "input" map(_ \ "@name" text)
- val doc = ConstructingParser.fromFile(new File("in.xhtml"), false).document
- val action = doc \\ "form" \ "@action" text
- val names = doc \\ "input" map(_ \ "@name" text)
- val doc = new XMLLoader[Node] {}.loadFile("in.xhtml")
- val action = doc \\ "form" \ "@action" text
- val names = doc \\ "input" map(_ \ "@name" text)
- val src = Source.fromFile("in.xhtml")
- try {
- val doc = XhtmlParser(src)
- val action = doc \\ "form" \ "@action" text
- val names = doc \\ "input" map(_ \ "@name" text)
- } finally {
- src.close
- }
順次読み込み
- var action = ""
- val names = new ListBuffer[String]
- val src = Source.fromFile("in.xhtml")
- try {
- new XMLEventReader(src).collect {
- case EvElemStart(_, "form", attrs, _) => action = attrs("action").text
- case EvElemStart(_, "input", attrs, _) => names += attrs("name").text
- }.foreach(_ => ())
- } finally {
- src.close
- }
- var action = ""
- val names = new ListBuffer[String]
- val src = Source.fromFile("in.xhtml")
- try {
- val reader = new XMLEventReader(src)
- for (EvElemStart(_, label, attrs, _) <- reader) label match {
- case "form" => action = attrs("action").text
- case "input" => names += attrs("name").text
- case _ => ()
- }
- } finally {
- src.close
- }
- var action = ""
- val names = new ListBuffer[String]
- XML.parser.parse(Source.fromFile("in.xhtml"), new DefaultHandler {
- override def startElement(uri: String, localName: String, name: String, attributes: Attributes) =
- name match {
- case "form" => action = attributes.getValue("action")
- case "input" => names += attributes.getValue("name")
- case _ => ()
- }
- })
Erlang
先に全部読む
- {Doc, _} = xmerl_scan:file("in.xhtml"),
- [ActionAttr|_] = xmerl_xpath:string("//form/@action", Doc),
- Action = ActionAttr#xmlAttribute.value,
- Names = [Attr#xmlAttribute.value || Attr <- xmerl_xpath:string("//input/@name", Doc)].
Haskell
Cabal の
MissingH、
xml を使った場合
先に全部読む
- contents <- readFile "in.xhtml"
- let Just doc = parseXMLDoc contents
- let Just formElem = findElement (QName "form" Nothing Nothing) doc
- let Just action = findAttr (QName "action" Nothing Nothing) formElem
- let names = map forceMaybe $ map (findAttr $ QName "name" Nothing Nothing) $ findElements (QName "input" Nothing Nothing) doc
Cabal の
HaXml を使った場合
先に全部読む
- contents <- readFile "in.xhtml"
- let Document _ _ root _ = xmlParse "" contents
- let find xpath root = map contentElem $ xtract id xpath $ CElem root noPos
- let getAttr name elem = head $ [value | (name', AttValue [Left value]) <- attrs elem, name' == name]
- let [action] = map (getAttr "action") $ find "//form" root
- let names = map (getAttr "name") $ find "//input" root
- contents <- readFile "in.xhtml"
- let Document _ _ root _ = xmlParse "" contents
- let find name root = map contentElem $ (deep $ tag name) $ CElem root noPos
- let getAttr name elem = head $ [value | (name', AttValue [Left value]) <- attrs elem, name' == name]
- let [action] = map (getAttr "action") $ find "form" root
- let names = map (getAttr "name") $ find "input" root
順次読み込み
- contents <- readFile "in.xhtml"
- let (elements, Nothing) = saxParse "" contents
- let map = foldl f (fromList [("names", [])]) elements where
- f map (SaxElementOpen "form" attrs) = foldl fForm map attrs
- f map (SaxElementTag "input" attrs) = foldl fInput map attrs
- f map _ = map
- fForm map ("action", AttValue [Left value]) = insert "action" [value] map
- fForm map _ = map
- fInput map ("name", AttValue [Left value]) = insert "names" (value : map ! "names") map
- fInput map _ = map
- let [action] = map ! "action"
- let names = reverse $ map ! "names"
PowerShell
先に全部読む
- [xml] $doc = cat in.xhtml
- $action = $doc.html.body.form.action
- $names = $doc.html.body.form.input | foreach { $_.name }
- [xml] $doc = cat in.xhtml
- $action = $doc.SelectSingleNode('//form/@action').Value
- $names = $doc.SelectNodes('//input/@name') | foreach { $_.Value }
順次読み込み
- $names = @()
- $reader = [System.Xml.XmlReader]::Create('in.xhtml')
- trap { $reader.Close() }
- while ($reader.Read()) {
- switch ($reader.NodeType) {
- 'Element' {
- switch ($reader.Name) {
- 'form' { $action = $reader.GetAttribute('action') }
- 'input' { $names += $reader.GetAttribute('name') }
- }
- }
- }
- }
- $reader.Close()
F#
先に全部読む
- let getAttr name (elem : XElement) = elem.Attribute(XName.Get name).Value
- let doc = XDocument.Load "in.xhtml"
- let action = doc.Descendants(XName.Get "form") |> Seq.head |> getAttr "action"
- let names = doc.Descendants(XName.Get "input") |> Seq.map (getAttr "name")
- let doc = new XmlDocument()
- doc.Load "in.xhtml"
- let action = doc.SelectSingleNode("//form/@action").Value
- let names = [for node in doc.SelectNodes "//input/@name" -> node.Value]
順次読み込み
- let mutable action = ""
- let names = new List<string>()
- use reader = XmlReader.Create "in.xhtml"
- while reader.Read() do
- match reader.NodeType with
- | XmlNodeType.Element ->
- match reader.Name with
- | "form" -> action <- reader.GetAttribute "action"
- | "input" -> names.Add(reader.GetAttribute "name")
- | _ -> ()
- | _ -> ()
C#
先に全部読む
- var doc = XDocument.Load("in.xhtml");
- string action = doc.Descendants("form").First().Attribute("action").Value;
- var names = doc.Descendants("input").Select(input => input.Attribute("name").Value);
- var doc = XDocument.Load("in.xhtml");
- string action = (from form in doc.Descendants("form")
- select form.Attribute("action").Value).First();
- var names = from input in doc.Descendants("input") select input.Attribute("name").Value;
- XmlDocument doc = new XmlDocument();
- doc.Load("in.xhtml");
- string action = doc.SelectSingleNode("//form/@action").Value;
- List<string> names = new List<string>();
- foreach (XmlNode node in doc.SelectNodes("//input/@name")) {
- names.Add(node.Value);
- }
順次読み込み
- string action = null;
- List<string> names = new List<string>();
- using (XmlReader reader = XmlReader.Create("in.xhtml")) {
- while (reader.Read()) {
- switch (reader.NodeType) {
- case XmlNodeType.Element:
- switch (reader.Name) {
- case "form":
- action = reader.GetAttribute("action");
- break;
- case "input":
- names.Add(reader.GetAttribute("name"));
- break;
- }
- break;
- }
- }
- }
Go
順次読み込み
- type InputTag struct {
- Name string `xml:"name,attr"`
- }
- type FormTag struct {
- Action string `xml:"action,attr"`
- Input []InputTag `xml:"input"`
- }
- var action string
- names := list.New()
- file, err := os.Open("in.xhtml")
- if err != nil { return err }
- defer file.Close()
- parser := xml.NewDecoder(file)
- for {
- token, err := parser.Token()
- if err == io.EOF { break }
- if err != nil { return err }
- startElem, ok := token.(xml.StartElement)
- if ok && startElem.Name.Local == "form" {
- var form FormTag
- err = parser.DecodeElement(&form, &startElem)
- if err != nil { return err }
- action = form.Action
- for _, input := range form.Input {
- names.PushBack(input.Name)
- }
- break
- }
- }
Ruby
先に全部読む
- doc = REXML::Document.new File.new('in.xhtml')
- action = doc.elements['//form/@action'].value
- names = doc.elements.collect('//input') {|input| input.attributes['name'] }
- doc = REXML::Document.new File.new('in.xhtml')
- form = doc.elements['//form']
- action = form.attributes['action']
- names = form.elements.collect('input') {|input| input.attributes['name'] }
先に全部読む
Nokogiri を使った場合
- doc = open('in.xhtml') {|file| Nokogiri file }
- action = doc.at(:form)[:action]
- names = (doc / :input).collect {|input| input[:name] }
- doc = open('in.xhtml') {|file| Nokogiri file }
- action = doc.search(:form).first.attr :action
- names = doc.search(:input).collect {|input| input.attr :name }
- doc = open('in.xhtml') {|file| Nokogiri file }
- action = doc.xpath('//form/@action').first.text
- names = doc.xpath('//input/@name').collect(&:text)
順次読み込み
- class << listener = {:names => []}
- include REXML::StreamListener
- def tag_start(name, attrs)
- case name
- when 'form'
- self[:action] = attrs['action']
- when 'input'
- self[:names] << attrs['name']
- end
- end
- end
- REXML::Parsers::StreamParser.new(File.read('in.xhtml'), listener).parse
- action = listener[:action]
- names = listener[:names]
順次読み込み
Nokogiri を使った場合
- action = nil
- names = []
- open 'in.xhtml' do |file|
- Nokogiri::XML::Reader(file).each do |node|
- case node.name
- when 'form'
- action = node.attribute 'action'
- when 'input'
- names << node.attribute('name')
- end
- end
- end
- class Document < Nokogiri::XML::SAX::Document
- attr_reader :action, :names
- def initialize
- @names = []
- end
- def start_element name, attrs
- attr_hash = Hash[*attrs.flatten]
- case name
- when 'form'
- @action = attr_hash['action']
- when 'input'
- @names << attr_hash['name']
- end
- end
- end
- xml = open('in.xhtml') {|file| file.read }
- doc = Document.new
- Nokogiri::XML::SAX::Parser.new(doc).parse(xml)
- action = doc.action
- names = doc.names
Python
先に全部読む
- tree = xml.etree.ElementTree.ElementTree()
- tree.parse('in.xhtml')
- form = tree.find('body/form')
- action = form.attrib['action']
- names = [input.attrib['name'] for input in form.findall('input')]
順次読み込み
- class Handler(xml.sax.handler.ContentHandler):
- action = ''
- names = []
- def startElement(self, name, attrs):
- if name == 'form':
- self.action = attrs['action']
- elif name == 'input':
- self.names.append(attrs['name'])
- handler = Handler()
- xml.sax.parse('in.xhtml', handler)
- action = handler.action
- names = handler.names
順次読み込み
Python 3.0以降
- class Parser(html.parser.HTMLParser):
- action = ''
- names = []
- def handle_starttag(self, tag, attrs):
- if tag == 'form':
- self.action = dict(attrs)['action']
- def handle_startendtag(self, tag, attrs):
- if tag == 'input':
- self.names.append(dict(attrs)['name'])
- parser = Parser()
- with open('in.xhtml', 'r') as file:
- parser.feed(file.read())
- action = parser.action
- names = parser.names
PHP
- $doc = new DOMDocument();
- if (! $doc->load('in.xhtml')) {
- throw new Exception('Cannot load in.xhtml');
- }
- $xpath = new DOMXPath($doc);
- $action = $xpath->evaluate('string(//form/@action)');
- $names = [];
- foreach ($xpath->query('//input') as $input) {
- array_push($names, $input->getAttribute('name'));
- }
- if (($xml = simplexml_load_file('in.xhtml')) === FALSE) {
- throw new Exception('Cannot load in.xhtml');
- }
- $form = $xml->xpath('//form');
- $action = (string)$form[0]['action'];
- $names = [];
- foreach ($xml->xpath('//input') as $input) {
- array_push($names, (string)$input['name']);
- }
Perl
CPAN の
XML::LibXML を使った場合
- my $doc = XML::LibXML->load_xml(location => 'in.xhtml');
- my $action = $doc->findvalue('//form/@action');
- my @names = map $_->value, $doc->findnodes('//input/@name');
CPAN の
XML::Simple を使った場合
- my $hash = XML::Simple->new->XMLin('in.xhtml');
- my $action = $hash->{body}{form}{action};
- my @names = keys %{$hash->{body}{form}{input}};
CPAN の
XML::TreePP を使った場合
- my $hash = XML::TreePP->new->parsefile('in.xhtml');
- my $action = $hash->{html}{body}{form}{-action};
- my @names = map $_->{-name}, @{$hash->{html}{body}{form}{input}};
人物リストのJSONデータから、20歳の人全員の名前を取得する。
Java
org.json パッケージを使った場合
- String jsonStr = "{'members': ["
- + "{'name': 'Taro', 'age': 20}, "
- + "{'name': 'Jiro', 'age': 17}, "
- + "{'name': 'Saburo', 'age': 15}, "
- + "{'name': 'Hanako', 'age': 20}"
- + "]}";
- List<String> result = new ArrayList<String>();
- JSONArray members = new JSONObject(jsonStr).getJSONArray("members");
- int length = members.length();
- for (int i = 0; i < length; i++) {
- JSONObject member = members.getJSONObject(i);
- if (member.getInt("age") == 20) {
- result.add(member.getString("name"));
- }
- }
Groovy
- def jsonStr = """
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }"""
- def all = new JsonSlurper().parseText(jsonStr)
- def result = all.members.findAll { it.age == 20 } *.name
org.json パッケージを使った場合
- def members = new JSONObject(jsonStr).members
- def memberList = (0 ..< members.length()).collect(members.&get)
- def result = memberList.findAll { it.age == 20 } *.name
Scala
- val json = """
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- """;
- val result = (JSON.parseFull(json): @unchecked) match {
- case Some(all: Map[String, List[Map[Any, Any]]]) =>
- for (member <- all("members"); if member("age") == 20) yield member("name")
- }
Haskell
Cabal の
json を使った場合
- let json = concat ["{",
- " \"members\": [",
- " {\"name\": \"Taro\", \"age\": 20},",
- " {\"name\": \"Jiro\", \"age\": 17},",
- " {\"name\": \"Saburo\", \"age\": 15},",
- " {\"name\": \"Hanako\", \"age\": 20}",
- " ]",
- "}"]
- let [(JSObject obj, "")] = readP_to_S p_value json
- let Just (JSArray members) = get_field obj "members" :: Maybe JSValue
- let result = [ name
- | JSObject member <- members
- , let Just (JSString (JSONString name)) = get_field member "name"
- , let Just (JSRational _ age) = get_field member "age"
- , age == 20]
PowerShell
Json.NET を使った場合
- $json = @'
- {
- 'members': [
- {'name': 'Taro', 'age': 20},
- {'name': 'Jiro', 'age': 17},
- {'name': 'Saburo', 'age': 15},
- {'name': 'Hanako', 'age': 20}
- ]
- }
- '@
- $jobj = [Newtonsoft.Json.Linq.JObject]::Parse($json)
- $result = $jobj['members'] | where { [int] $_['age'] -eq 20 } | foreach { $_['name'].Value }
F#
- let json = @"
- {
- ""members"": [
- {""name"": ""Taro"", ""age"": 20},
- {""name"": ""Jiro"", ""age"": 17},
- {""name"": ""Saburo"", ""age"": 15},
- {""name"": ""Hanako"", ""age"": 20}
- ]
- }"
- type All =
- val mutable members : Member[]
- and Member =
- val mutable name : string
- val mutable age : int
- let stream = new MemoryStream(Encoding.UTF8.GetBytes json)
- let all = (DataContractJsonSerializer typeof<All>).ReadObject stream :?> All
- let result = [
- for _member in all.members do
- if _member.age = 20 then yield _member.name
- ]
Json.NET を使った場合
- let jobj = JObject.Parse json
- let result = [
- for _member in jobj.["members"] do
- if int _member.["age"] = 20 then yield string <| _member.Value "name"
- ]
C#
- var json = @"
- {
- ""members"": [
- {""name"": ""Taro"", ""age"": 20},
- {""name"": ""Jiro"", ""age"": 17},
- {""name"": ""Saburo"", ""age"": 15},
- {""name"": ""Hanako"", ""age"": 20}
- ]
- }";
- [DataContract]
- public class All {
- [DataMember]
- public Member[] members { get; private set; }
- [DataContract]
- public class Member {
- [DataMember]
- public string name { get; private set; }
- [DataMember]
- public int age { get; private set; }
- }
- }
- var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
- var all = (All)new DataContractJsonSerializer(typeof(All)).ReadObject(stream);
- var result = from member in all.members
- where member.age == 20
- select member.name;
Json.NET を使った場合
- var jobj = JObject.Parse(json);
- var result = from member in jobj["members"]
- where (int)member["age"] == 20
- select (string)member["name"];
Go
- jsonStr := `
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }`
- type All struct {
- Members []Member `json:"members"`
- }
- type Member struct {
- Name string `json:"name"`
- Age int `json:"age"`
- }
- var all All
- result := list.New()
- decoder := json.NewDecoder(strings.NewReader(jsonStr))
- err := decoder.Decode(&all)
- if err != nil { return err }
- for _, member := range all.Members {
- if member.Age == 20 {
- result.PushBack(member.Name)
- }
- }
Rust
serde・serde_json を使った場合
- #[derive(serde::Serialize, serde::Deserialize)]
- struct Person<'a> {
- name: &'a str,
- age: i32,
- }
- let json = r#"
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- "#;
- let map: HashMap<&str, Vec<Person>> = serde_json::from_str(json).unwrap();
- let result: Vec<_> = map["members"].iter().filter(|p| p.age == 20).map(|p| p.name).collect();
TypeScript
- let json = `
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15}
- ]
- }
- `;
- let all = JSON.parse(json);
- let result = all.members
- .filter(member => member.age === 20)
- .map(member => member.name);
JavaScript
- let json = `
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15}
- ]
- }
- `;
- let all = JSON.parse(json);
- let result = all.members
- .filter(member => member.age === 20)
- .map(member => member.name);
CoffeeScript
- json = '''
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15}
- ]
- }
- '''
- all = JSON.parse json
- result = all.members
- .filter (member) -> member.age == 20
- .map (member) -> member.name
Ruby
Ruby on Rails を使った場合
- json = <<'END'
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- END
- all = ActiveSupport::JSON::decode json
- result = all['members'].select {|m| m['age'] == 20 }.collect {|m| m['name'] }
Python
- json_str = '''
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- '''
- all = json.loads(json_str)
- result = [m['name'] for m in all['members'] if m['age'] == 20]
PHP
- $json = <<<'END'
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- END;
- if (($all = json_decode($json)) === NULL) {
- throw new Exception('Cannot decode');
- }
- $result = array_filter($all->members, function($member) { return $member->age === 20; });
- $result = array_map(function($member) { return $member->name; }, $result);
Perl
CPAN の
JSON を使った場合
- my $json = <<'END';
- {
- "members": [
- {"name": "Taro", "age": 20},
- {"name": "Jiro", "age": 17},
- {"name": "Saburo", "age": 15},
- {"name": "Hanako", "age": 20}
- ]
- }
- END
- my $all = decode_json($json);
- my @result = map $_->{name}, grep $_->{age} == 20, @{$all->{members}};
Java
- HttpClient client = HttpClient.newHttpClient();
- HttpRequest request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/")).GET().build();
- String result = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
Apache HttpClient 5.xを使った場合
- String result = Request.get("http://www.***.ne.jp/").execute().returnContent().asString();
Commons IO を使った場合
- String result = IOUtils.toString(new URL("http://www.***.ne.jp/"), "UTF-8");
Groovy
- def result = new URL('http://www.***.ne.jp/').getText('UTF-8')
Kotlin
- val client = HttpClient.newHttpClient()
- val request = HttpRequest.newBuilder(URI("http://www.***.ne.jp/")).GET().build()
- val result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
- val result = Request.get("http://www.***.ne.jp/").execute().returnContent().asString()
Commons IO を使った場合
- val result = IOUtils.toString(URL("http://www.***.ne.jp/"), "UTF-8")
Scala
- val result = new URL("http://www.***.ne.jp/").cat !!
- val src = Source.fromURL("http://www.***.ne.jp/", "UTF-8")
- val result = try { src.mkString } finally { src.close }
Dispatch を使った場合
- val http = new Http
- val result = http(url("http://www.***.ne.jp/") >\ "UTF-8" as_str)
scalaj-http を使った場合
- val result = Http("http://www.***.ne.jp/").asString
scala-io を使った場合
- val result = new URL("http://www.***.ne.jp").asInput.slurpString(Codec.UTF8)
- val result = Resource.fromURL("http://www.***.ne.jp").slurpString(Codec.UTF8)
Erlang
- inets:start(),
- {ok, {{_, 200, _}, _, Result}} = httpc:request("http://www.***.ne.jp/").
Haskell
Cabal の
HTTP を使った場合
- Right (Response (2, 0, 0) _ _ result) <- simpleHTTP $ getRequest "http://www.***.ne.jp/"
PowerShell
- $bytes = (New-Object System.Net.WebClient).DownloadData('http://www.***.ne.jp')
- $result = [System.Text.Encoding]::UTF8.GetString($bytes)
F#
- let result = (new WebClient()).DownloadData "http://www.***.ne.jp/" |> Encoding.UTF8.GetString
C#
- byte[] bytes = new WebClient().DownloadData("http://www.***.ne.jp/");
- string result = Encoding.UTF8.GetString(bytes);
Go
- response, err := http.Get("http://www.***.ne.jp/")
- if err != nil { return err }
- defer response.Body.Close()
- if response.StatusCode == http.StatusOK {
- var buf bytes.Buffer
- var bytes [1024]byte
- for {
- n, err := response.Body.Read(bytes[:])
- if err == io.EOF { break }
- if err != nil { return err }
- buf.Write(bytes[:n])
- }
- result := buf.String()
- }
Rust
reqwest を使った場合
- let response = reqwest::get("http://www.***.ne.jp/").await.unwrap();
- let result = response.text().await.unwrap();
Ruby
- result = URI.open('http://www.***.ne.jp/') {|io| io.read }
- result = Net::HTTP.get_response(URI.parse('http://www.***.ne.jp/')).body
- result = Net::HTTP.start('www.***.ne.jp', 80) {|http| http.get('/').body }
Python
- with urllib.request.urlopen('http://www.***.ne.jp/') as response:
- result = response.read().decode('UTF-8')
- conn = http.client.HTTPConnection('www.***.ne.jp')
- conn.request('GET', '/')
- try:
- response = conn.getresponse()
- if response.status == http.client.OK:
- result = response.read().decode('UTF-8')
- finally:
- conn.close()
PHP
- if (($result = file_get_contents('http://www.***.ne.jp/')) === FALSE) {
- $error = error_get_last();
- throw new Exception($error['message']);
- }
- $ch = curl_init('http://www.***.ne.jp/');
- curl_setopt_array($ch, [
- CURLOPT_FAILONERROR => TRUE,
- CURLOPT_RETURNTRANSFER => TRUE
- ]);
- $result = curl_exec($ch);
- $error = $result === FALSE ? curl_error($ch) : NULL;
- curl_close($ch);
- if ($error) {
- throw new Exception($error);
- }
Perl
- my $response = LWP::UserAgent->new->get('http://www.***.ne.jp/');
- die $response->request->uri . ': ' . $response->status_line unless $response->is_success;
- my $result = $response->content;
Java
- HttpClient client = HttpClient.newHttpClient();
- String data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password";
- HttpRequest request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
- .POST(HttpRequest.BodyPublishers.ofString(data))
- .build();
- String result = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
Apache HttpClient 5.xを使った場合
- String result = Request.post("http://www.***.ne.jp/")
- .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
- .execute().returnContent().asString();
Groovy
- def client = HttpClient.newHttpClient()
- def data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
- def request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
- .POST(HttpRequest.BodyPublishers.ofString(data))
- .build()
- def result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
- def result = Request.post("http://www.***.ne.jp/")
- .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
- .execute().returnContent().asString()
Kotlin
- val client = HttpClient.newHttpClient()
- val data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
- val request = HttpRequest.newBuilder(URI("http://www.***.ne.jp/"))
- .POST(HttpRequest.BodyPublishers.ofString(data))
- .build()
- val result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
- val result = Request.post("http://www.***.ne.jp/")
- .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
- .execute().returnContent().asString()
Scala
- val client = HttpClient.newHttpClient
- val data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
- val request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
- .POST(HttpRequest.BodyPublishers ofString data)
- .build
- val result = client.send(request, HttpResponse.BodyHandlers.ofString).body
Apache HttpClient 5.xを使った場合
- val result = Request.post("http://www.***.ne.jp/")
- .bodyForm(Form.form.add("NAME", "名前").add("PASSWORD", "password").build, StandardCharsets.UTF_8)
- .execute.returnContent.asString
Dispatch を使った場合
- val http = new Http
- val params = List("NAME" -> "名前", "PASSWORD" -> "password")
- val result = http(url("http://www.***.ne.jp/") << params >\ "UTF-8" as_str)
scalaj-http を使った場合
- val params = List("NAME" -> "名前", "PASSWORD" -> "password")
- val result = Http.post("http://www.***.ne.jp/").params(params).asString
Erlang
- inets:start(),
- Request = {
- "http://www.***.ne.jp",
- [],
- "application/x-www-form-urlencoded",
- "NAME=" ++ edoc_lib:escape_uri("名前") ++ "&PASSWORD=password"
- },
- {ok, {{_, 200, _}, _, Result}} = httpc:request(post, Request, [], []).
Haskell
Cabal の
HTTP を使った場合
- let Just uri = parseURI("http://www.***.ne.jp/")
- let body = urlEncodeVars [("NAME", "名前"), ("PASSWORD", "password")]
- let headers = [Header HdrContentType "application/x-www-form-urlencoded",
- Header HdrContentLength $ show $ length body
- ]
- let request = Request uri POST headers body
- Right (Response (2, 0, 0) _ _ result) <- simpleHTTP request
PowerShell
- $request = [System.Net.WebRequest]::Create('http://www.***.ne.jp/')
- $request.Method = 'POST'
- $request.ContentType = 'application/x-www-form-urlencoded'
- $paramDict = @{NAME = '名前'; PASSWORD = 'password'}
- $body = [string]::Join('&', ($paramDict.Keys | foreach { $_ + '=' + [System.Web.HttpUtility]::UrlEncode($paramDict[$_], [System.Text.Encoding]::UTF8) }))
- $writer = New-Object System.IO.StreamWriter($request.GetRequestStream(), [System.Text.Encoding]::ASCII)
- &{
- $writer.Write($body)
- $writer.Close()
- trap { $writer.Close(); break }
- }
- $response = $request.GetResponse()
- &{
- $reader = New-Object System.IO.StreamReader($response.GetResponseStream(), [System.Text.Encoding]::UTF8)
- &{
- $result = $reader.ReadToEnd()
- $reader.Close()
- trap { $reader.Close(); break }
- }
- $response.Close()
- trap { $response.Close(); break }
- }
F#
- let request = WebRequest.Create "http://www.***.ne.jp/"
- request.Method <- "POST"
- request.ContentType <- "application/x-www-form-urlencoded"
- let paramMap = Map.ofList [("NAME", "名前"); ("PASSWORD", "password")]
- let body = String.Join("&",
- paramMap |> Seq.map (fun pair -> pair.Key + "=" + HttpUtility.UrlEncode(pair.Value, Encoding.UTF8)))
- let writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)
- try
- writer.Write body
- finally
- writer.Close()
- use response = request.GetResponse()
- use reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)
- let result = reader.ReadToEnd()
C#
- var request = WebRequest.Create("http://www.***.ne.jp/");
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- var paramDict = new Dictionary<string, string> {{"NAME", "名前"}, {"PASSWORD", "password"}};
- var body = string.Join("&",
- from pair in paramDict
- select pair.Key + "=" + HttpUtility.UrlEncode(pair.Value, Encoding.UTF8));
- using (var writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)) {
- writer.Write(body);
- }
- using (var response = request.GetResponse()) {
- using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) {
- string result = reader.ReadToEnd();
- }
- }
Go
- params := map[string][]string{
- "NAME":[]string{"名前"},
- "PASSWORD":[]string{"password"}
- }
- response, err := http.PostForm("http://www.***.ne.jp/", params)
- if err != nil { return err }
- defer response.Body.Close()
- if response.StatusCode == http.StatusOK {
- var buf bytes.Buffer
- var bytes [1024]byte
- for {
- n, err := response.Body.Read(bytes[:])
- if err == io.EOF { break }
- if err != nil { return err }
- buf.Write(bytes[:n])
- }
- result := buf.String()
- }
Rust
reqwest を使った場合
- let client = reqwest::Client::new();
- let params = [("NAME", "名前"), ("PASSWORD", "password")];
- let response = client.post("http://www.***.ne.jp/").form(¶ms).send().await.unwrap();
- let result = response.text().await.unwrap();
Ruby
- response = Net::HTTP.post_form URI.parse('http://www.***.ne.jp/'), :NAME => '名前', :PASSWORD => 'password'
- result = response.body
Python
- body = urllib.parse.urlencode({'NAME': '名前', 'PASSWORD': 'password'})
- response = urllib.request.urlopen('http://www.***.ne.jp/', body)
- try:
- result = response.read().decode('UTF-8')
- finally:
- response.close()
- body = urllib.parse.urlencode({'NAME': '名前', 'PASSWORD': 'password'})
- conn = http.client.HTTPConnection('www.***.ne.jp')
- conn.request('POST', '/', body, {'Content-Type': 'application/x-www-form-urlencoded'})
- try:
- response = conn.getresponse()
- if response.status == http.client.OK:
- result = response.read().decode('UTF-8')
- finally:
- conn.close()
PHP
- $ch = curl_init('http://www.***.ne.jp/');
- curl_setopt_array($ch, [
- CURLOPT_FAILONERROR => TRUE,
- CURLOPT_POST => TRUE,
- CURLOPT_POSTFIELDS => ['NAME' => '名前', 'PASSWORD' => 'password'],
- CURLOPT_RETURNTRANSFER => TRUE
- ]);
- $result = curl_exec($ch);
- $error = $result === FALSE ? curl_error($ch) : NULL;
- curl_close($ch);
- if ($error) {
- throw new Exception($error);
- }
Perl
- my $response = LWP::UserAgent->new->post('http://www.***.ne.jp/', {NAME => '名前', PASSWORD => 'password'});
- die $response->request->uri . ': ' . $response->status_line unless $response->is_success;
- my $result = $response->content;
サーバ証明書にルートCAの署名がされていなかったり、発行先名がアクセス先と異なっていても良しとする場合。
Java
- public class IrresponsibleHostnameVerifier implements HostnameVerifier {
- @Override
- public boolean verify(String hostname, SSLSession session) { return true; }
- }
- public class IrresponsibleX509TrustManager implements X509TrustManager {
- @Override
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public X509Certificate[] getAcceptedIssuers() { return null; }
- }
- Authenticator.setDefault(new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- switch (getRequestorType()) {
- case PROXY:
- return new PasswordAuthentication("proxyUserName", "proxyPassword".toCharArray());
- case SERVER:
- return new PasswordAuthentication("wwwUserName", "wwwPassword".toCharArray());
- }
- return null;
- }
- });
- URL url = new URL("https://www.***.ne.jp/");
- Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.***.ne.jp", 80));
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
- try {
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(5000);
- connection.setRequestProperty("User-Agent", "Mozilla/4.0");
- SSLContext context = SSLContext.getInstance("SSL");
- context.init(null, new TrustManager[] {new IrresponsibleX509TrustManager()}, null);
- connection.setSSLSocketFactory(context.getSocketFactory());
- connection.setHostnameVerifier(new IrresponsibleHostnameVerifier());
- try (InputStream in = connection.getInputStream()) {
- try (FileOutputStream out = new FileOutputStream("index.html")) {
- in.transferTo(out);
- }
- }
- } finally {
- connection.disconnect();
- }
Apache HttpClient 4.xを使った場合
- public class IrresponsibleX509TrustManager implements X509TrustManager {
- @Override
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public X509Certificate[] getAcceptedIssuers() { return null; }
- }
- DefaultHttpClient client = new DefaultHttpClient();
- HttpParams params = client.getParams();
- params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80));
- params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
- params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
- BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
- credsProvider.setCredentials(new AuthScope("proxy.***.ne.jp", 80),
- new UsernamePasswordCredentials("proxyUserName", "proxyPassword"));
- credsProvider.setCredentials(new AuthScope("www.***.ne.jp", 443),
- new UsernamePasswordCredentials("wwwUserName", "wwwPassword"));
- client.setCredentialsProvider(credsProvider);
- SSLContext context = SSLContext.getInstance("SSL");
- context.init(null, new TrustManager[] {new IrresponsibleX509TrustManager()}, null);
- SSLSocketFactory socketFactory
- = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
- HttpGet get = new HttpGet("https://www.***.ne.jp/");
- get.setHeader("User-Agent", "Mozilla/4.0");
- client.execute(get, new ResponseHandler<Void>() {
- @Override
- public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
- StatusLine statusLine = response.getStatusLine();
- switch (statusLine.getStatusCode()) {
- case HttpStatus.SC_OK:
- try (FileOutputStream out = new FileOutputStream("index.html")) {
- response.getEntity().writeTo(out);
- }
- return null;
- default:
- throw new IOException(statusLine.toString());
- }
- }
- });
Groovy
- Authenticator.default = new Authenticator() {
- @Override PasswordAuthentication getPasswordAuthentication() {
- switch (requestorType) {
- case Authenticator.RequestorType.PROXY:
- return new PasswordAuthentication('proxyUserName', 'proxyPassword')
- case Authenticator.RequestorType.SERVER:
- return new PasswordAuthentication('wwwUserName', 'wwwPassword')
- }
- null
- }
- }
- def url = new URL('https://www.***.ne.jp/')
- def proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress('proxy.***.ne.jp', 80))
- def connection = url.openConnection(proxy)
- try {
- connection.connectTimeout = 5000
- connection.readTimeout = 5000
- connection.setRequestProperty 'User-Agent', 'Mozilla/4.0'
- def context = SSLContext.getInstance('SSL')
- def trustManager = [
- checkClientTrusted: { chain, authType -> },
- checkServerTrusted: { chain, authType -> },
- getAcceptedIssuers: {}
- ] as X509TrustManager
- context.init null, [trustManager] as TrustManager[], null
- connection.SSLSocketFactory = context.socketFactory
- connection.hostnameVerifier = { true } as HostnameVerifier
- connection.inputStream.withStream { input ->
- new File('index.html').withOutputStream { it << input }
- }
- } finally {
- connection.disconnect()
- }
Apache HttpClient 4.xを使った場合
- def client = new DefaultHttpClient()
- def params = client.params
- params.setParameter ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80)
- params.setParameter CoreConnectionPNames.CONNECTION_TIMEOUT, 5000
- params.setParameter CoreConnectionPNames.SO_TIMEOUT, 5000
- def credsProvider = new BasicCredentialsProvider()
- credsProvider.setCredentials new AuthScope("proxy.***.ne.jp", 80),
- new UsernamePasswordCredentials("proxyUserName", "proxyPassword")
- credsProvider.setCredentials new AuthScope("www.***.ne.jp", 443),
- new UsernamePasswordCredentials("wwwUserName", "wwwPassword")
- client.credentialsProvider = credsProvider
- def context = SSLContext.getInstance('SSL')
- def trustManager = [
- checkClientTrusted: { chain, authType -> },
- checkServerTrusted: { chain, authType -> },
- getAcceptedIssuers: {}
- ] as X509TrustManager
- context.init null, [trustManager] as TrustManager[], null
- def socketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
- client.connectionManager.schemeRegistry.register new Scheme("https", 443, socketFactory)
- def get = new HttpGet("https://www.***.ne.jp/")
- get.setHeader "User-Agent", "Mozilla/4.0"
- client.execute get, new ResponseHandler() {
- @Override def handleResponse(HttpResponse response) {
- def statusLine = response.statusLine
- switch (statusLine.statusCode) {
- case HttpStatus.SC_OK:
- new File("index.html").withOutputStream { response.entity.writeTo it }
- return
- default:
- throw new IOException(statusLine.toString())
- }
- }
- }
Scala
- class IrresponsibleHostnameVerifier extends HostnameVerifier {
- override def verify(hostname: String, session: SSLSession) = true
- }
- class IrresponsibleX509TrustManager extends X509TrustManager {
- override def checkClientTrusted(chain: Array[X509Certificate], authType: String) {}
- override def checkServerTrusted(chain: Array[X509Certificate], authType: String) {}
- override val getAcceptedIssuers = null
- }
- def tryWith[A <: {def close()}, B](a: A)(f: A => B) = try f(a) finally a.close
- Authenticator.setDefault(new Authenticator {
- import Authenticator.RequestorType._
- override def getPasswordAuthentication = getRequestorType match {
- case PROXY => new PasswordAuthentication("proxyUserName", "proxyPassword".toCharArray)
- case SERVER => new PasswordAuthentication("wwwUserName", "wwwPassword".toCharArray)
- }
- })
- val url = new URL("https://www.***.ne.jp/")
- val proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.***.ne.jp", 80))
- val connection = url.openConnection(proxy).asInstanceOf[HttpsURLConnection]
- try {
- connection.setConnectTimeout(5000)
- connection.setReadTimeout(5000)
- connection.setRequestProperty("User-Agent", "Mozilla/4.0")
- val context = SSLContext.getInstance("SSL")
- context.init(null, Array(new IrresponsibleX509TrustManager), null)
- connection.setSSLSocketFactory(context.getSocketFactory)
- connection.setHostnameVerifier(new IrresponsibleHostnameVerifier)
- tryWith (connection.getInputStream) { in =>
- tryWith (new FileOutputStream("index.html")) { out =>
- in.transferTo(out)
- }
- }
- } finally {
- connection.disconnect
- }
Dispatch と
scala-io を使った場合
- class IrresponsibleX509TrustManager extends X509TrustManager {
- override def checkClientTrusted(chain: Array[X509Certificate], authType: String) {}
- override def checkServerTrusted(chain: Array[X509Certificate], authType: String) {}
- override val getAcceptedIssuers = null
- }
- val http = new Http
- val client = http.client.asInstanceOf[DefaultHttpClient]
- val params = client.getParams
- params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80))
- params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
- params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
- val credsProvider = new BasicCredentialsProvider
- credsProvider.setCredentials(new AuthScope("proxy.***.ne.jp", 80),
- new UsernamePasswordCredentials("proxyUserName", "proxyPassword"))
- credsProvider.setCredentials(new AuthScope("www.***.ne.jp", 443),
- new UsernamePasswordCredentials("wwwUserName", "wwwPassword"))
- client.setCredentialsProvider(credsProvider)
- val context = SSLContext.getInstance("SSL")
- context.init(null, Array(new IrresponsibleX509TrustManager), null)
- val socketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
- client.getConnectionManager.getSchemeRegistry.register(new Scheme("https", 443, socketFactory))
- val headers = Map("User-Agent" -> "Mozilla/4.0")
- http(url("https://www.***.ne.jp/") <:< headers >> { _.asInput copyDataTo Path("index.html") })
PowerShell
- $proxy = New-Object System.Net.WebProxy (New-Object System.Uri http://proxy.***.ne.jp)
- $proxy.Credentials = New-Object System.Net.NetworkCredential proxyUserName, proxyPassword
- $request = [System.Net.WebRequest]::Create("https://www.***.ne.jp/")
- $request.Proxy = $proxy
- $request.Timeout = 5000
- $request.ReadWriteTimeout = 5000
- $request.UserAgent = "Mozilla/4.0"
- $request.Credentials = New-Object System.Net.NetworkCredential wwwUserName, wwwPassword
- [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
- $response = $request.GetResponse()
- &{
- switch ($response.StatusCode) {
- 'OK' {
- $responseStream = $response.GetResponseStream()
- &{
- $fileStream = New-Object System.IO.FileStream index.html, OpenOrCreate
- &{
- $buf = New-Object byte[] 1024
- for (;;) {
- $count = $responseStream.Read($buf, 0, $buf.Length)
- if ($count -le 0) { break }
- $fileStream.Write($buf, 0, $count)
- }
- $fileStream.Close()
- trap { $fileStream.Close(); break }
- }
- $responseStream.Close()
- trap { $responseStream.Close(); break }
- }
- }
- }
- $response.Close()
- trap { $response.Close(); break }
- }
F#
- let proxy = new WebProxy(new System.Uri "http://proxy.***.ne.jp")
- proxy.Credentials <- new NetworkCredential("proxyUserName", "proxyPassword")
- let request = WebRequest.Create "https://www.***.ne.jp/" :?> HttpWebRequest
- request.Proxy <- proxy
- request.Timeout <- 5000
- request.ReadWriteTimeout <- 5000
- request.UserAgent <- "Mozilla/4.0"
- request.Credentials <- new NetworkCredential("wwwUserName", "wwwPassword")
- ServicePointManager.ServerCertificateValidationCallback <- fun _ _ _ _ -> true
- use response = request.GetResponse() :?> HttpWebResponse
- match response.StatusCode with
- | HttpStatusCode.OK ->
- use responseStream = response.GetResponseStream()
- use fileStream = new FileStream("index.html", FileMode.OpenOrCreate)
- let buf = Array.zeroCreate<byte> 1024
- let rec readWrite() =
- let count = responseStream.Read(buf, 0, buf.Length)
- if count > 0 then
- fileStream.Write(buf, 0, count)
- readWrite()
- readWrite()
- | _ -> ()
C#
- var proxy = new WebProxy(new Uri("http://proxy.***.ne.jp"));
- proxy.Credentials = new NetworkCredential("proxyUserName", "proxyPassword");
- var request = (HttpWebRequest)WebRequest.Create("https://www.***.ne.jp/");
- request.Proxy = proxy;
- request.Timeout = 5000;
- request.ReadWriteTimeout = 5000;
- request.UserAgent = "Mozilla/4.0";
- request.Credentials = new NetworkCredential("wwwUserName", "wwwPassword");
- ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
- using (var response = (HttpWebResponse)request.GetResponse()) {
- switch (response.StatusCode) {
- case HttpStatusCode.OK:
- using (var responseStream = response.GetResponseStream()) {
- using (var fileStream = new FileStream("index.html", FileMode.OpenOrCreate)) {
- var buf = new byte[1024];
- int count;
- while ((count = responseStream.Read(buf, 0, buf.Length)) > 0) {
- fileStream.Write(buf, 0, count);
- }
- }
- }
- break;
- }
- }
Ruby
- http = Net::HTTP.new 'www.***.ne.jp', 443, 'proxy.***.ne.jp', 80, 'proxyUserName', 'proxyPassword'
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- http.open_timeout = 5
- http.read_timeout = 5
- request = Net::HTTP::Get.new '/'
- request.basic_auth 'wwwUserName', 'wwwPassword'
- request['User-Agent'] = 'Mozilla/4.0'
- verbose = $VERBOSE
- $VERBOSE = nil
- begin
- http.request request do |response|
- open 'index.html', 'wb' do |file|
- response.read_body {|chunk| file.write chunk }
- end
- end
- ensure
- $VERBOSE = verbose
- end
Python
- proxy_h = ProxyHandler({'https': 'http://proxy.***.ne.jp'})
- proxy_auth_h = ProxyBasicAuthHandler(HTTPPasswordMgrWithDefaultRealm())
- proxy_auth_h.add_password(None, 'http://proxy.***.ne.jp', 'proxyUserName', 'proxyPassword')
- auth_h = HTTPBasicAuthHandler(HTTPPasswordMgrWithDefaultRealm())
- auth_h.add_password(None, 'https://www.***.ne.jp/', 'wwwUserName', 'wwwPassword')
- opener = build_opener(proxy_h, proxy_auth_h, auth_h)
- opener.addheaders = [('User-Agent', 'Mozilla/4.0')]
- response = opener.open('https://www.***.ne.jp/', None, 5)
- try:
- with open('index.html', 'wb') as f:
- while True:
- bytes = response.read(1024)
- if len(bytes) == 0:
- break
- f.write(bytes)
- finally:
- response.close()
PHP
- $ch = curl_init('https://www.***.ne.jp/');
- $f = fopen('index.html', 'w');
- curl_setopt_array($ch, [
- CURLOPT_FILE => $f,
- CURLOPT_TIMEOUT => 5,
- CURLOPT_FAILONERROR => TRUE,
- CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
- CURLOPT_USERPWD => 'wwwUserName:wwwPassword',
- CURLOPT_PROXY => 'http://proxy.***.ne.jp',
- CURLOPT_PROXYAUTH => CURLAUTH_BASIC,
- CURLOPT_PROXYUSERPWD => 'proxyUserName:proxyPassword',
- CURLOPT_SSL_VERIFYPEER => FALSE,
- CURLOPT_SSL_VERIFYHOST => 0,
- CURLOPT_USERAGENT => 'Mozilla/4.0'
- ]);
- $error = curl_exec($ch) === FALSE ? curl_error($ch) : NULL;
- curl_close($ch);
- flose($f);
- if ($error !== NULL) {
- unlink('index.html');
- throw new Exception($error);
- }
Perl
- $ENV{HTTPS_PROXY} = 'http://proxy.***.ne.jp';
- $ENV{HTTPS_PROXY_USERNAME} = 'proxyUserName';
- $ENV{HTTPS_PROXY_PASSWORD} = 'proxyPassword';
- my $request = HTTP::Request->new('GET', 'https://www.***.ne.jp/');
- $request->authorization_basic('wwwUserName', 'wwwPassword');
- my $ua = LWP::UserAgent->new(agent => 'Mozilla/4.0', timeout => 5);
- $ua->env_proxy;
- my $response = $ua->request($request, 'index.html');
- unless ($response->is_success) {
- unlink 'index.html';
- die $response->request->uri . ': ' . $response->status_line;
- }