プログラミング言語の比較 > ファイルとディレクトリ、通信

ディレクトリの直下にあるファイルとサブディレクトリの名前を出力する

Java

  1. // import java.io.File;
  2. for (File file : new File("/tmp").listFiles()) {
  3. System.out.println(file);
  4. }
  1. // import java.nio.file.*;
  2. // import java.util.stream.Stream;
  3. Path dir = Path.of("/tmp");
  4. try (Stream<Path> stream = Files.list(dir)) {
  5. stream.forEach(System.out::println);
  6. }

Groovy

  1. new File('/tmp').eachFile { println it }

Kotlin

  1. // import java.io.File
  2. File("/tmp").listFiles().forEach(::println)
  1. // import java.nio.file.Files
  2. // import java.nio.file.Path
  3. val path = Path.of("/tmp")
  4. Files.list(path).use { it.forEach(::println) }

Scala

  1. // import java.io.File
  2. new File("/tmp").listFiles.foreach(println)
scala-io を使った場合
  1. // import scalax.file.Path
  2. // import scalax.file.PathMatcher.All
  3. for (path <- Path("/tmp") * All) println(path.name)

Erlang

  1. lists:foreach(fun(File) -> io:format("~s~n", [File]) end, filelib:wildcard("/tmp/*")).

Haskell

  1. -- import Directory
  2. getDirectoryContents "/tmp" >>= mapM_ putStrLn
  1. -- import Directory
  2. contents <- getDirectoryContents "/tmp"
  3. mapM_ putStrLn contents

PowerShell

  1. $dir = [System.IO.DirectoryInfo] '/tmp'
  2. $dir.GetFiles() + $dir.GetDirectories() | foreach { $_.FullName }
  1. $dir = [System.IO.DirectoryInfo] '/tmp'
  2. @($dir.GetFiles(); $dir.GetDirectories()) | foreach { $_.FullName }

F#

  1. // open System.IO
  2. let files = Directory.EnumerateFileSystemEntries "/tmp"
  3. for file in files do printfn "%s" file
  1. // open System.IO
  2. let dir = new DirectoryInfo "/tmp"
  3. for file in dir.EnumerateFileSystemInfos() do printfn "%s" file.FullName
  1. // open System.IO
  2. let dir = new DirectoryInfo "/tmp"
  3. let files = seq<FileSystemInfo> {
  4. yield! Seq.cast <| dir.GetFiles() // ファイル(FileInfo)を FileSystemInfo として列挙
  5. yield! Seq.cast <| dir.GetDirectories() // ディレクトリ(DirectoryInfo)を FileSystemInfo として列挙
  6. }
  7. for file in files do printfn "%s" file.FullName

C#

  1. // using System.IO;
  2. var files = Directory.EnumerateFileSystemEntries("/tmp");
  3. foreach (var file in files) {
  4. Console.WriteLine(file);
  5. }
  1. // using System.IO;
  2. var dir = new DirectoryInfo("/tmp");
  3. foreach (var file in dir.EnumerateFileSystemInfos()) {
  4. Console.WriteLine(file.FullName);
  5. }

C++

  1. #include <dirent.h>
  2. if (DIR* dir = opendir("/tmp")) {
  3. while (struct dirent* ent = readdir(dir)) {
  4. string name = ent->d_name;
  5. if (name != "." && name != "..") {
  6. cout << name << endl;
  7. }
  8. }
  9. closedir(dir);
  10. }
Boost を使った場合
  1. #include <boost/filesystem/operations.hpp>
  2. // using namespace boost::filesystem;
  3. directory_iterator end;
  4. for (directory_iterator it(path("/tmp")); it != end; it++) {
  5. cout << it->path().filename().string() << endl;
  6. }

Go

  1. // import "io/ioutil"
  2. files, err := ioutil.ReadDir("/tmp")
  3. if err != nil { return err }
  4. for _, file := range files {
  5. fmt.Printf("%s\n", file.Name())
  6. }
  1. // import "os"
  2. dir, err := os.Open("/tmp")
  3. if err != nil { return err }
  4. defer dir.Close()
  5. files, err := dir.Readdir(-1) // ディレクトリの内容を、件数制限なしで読み取る
  6. if err != nil { return err }
  7. for _, file := range files {
  8. fmt.Printf("%s\n", file.Name())
  9. }

Rust

  1. // use std::fs;
  2. let entries = fs::read_dir("/tmp").unwrap();
  3. for entry in entries {
  4. println!("{}", entry.unwrap().file_name().to_string_lossy());
  5. }

TypeScript

Node.js の場合
  1. // import * as fs from 'fs';
  2. let files = fs.readdirSync('/tmp');
  3. for (let i in files) {
  4. console.log(files[i]);
  5. }

JavaScript

Node.js の場合
  1. // const fs = require('fs');
  2. let files = fs.readdirSync('/tmp');
  3. for (let i in files) {
  4. console.log(files[i]);
  5. }

CoffeeScript

Node.js の場合
  1. # fs = require 'fs'
  2. for file in fs.readdirSync '/tmp'
  3. console.log file

Ruby

  1. puts Dir.glob('/tmp/*')
  1. puts Dir['/tmp/*']
  1. puts Dir.children('/tmp')
  1. Dir.each_child('/tmp') {|f| puts f }

Python

  1. # import os
  2. for f in os.listdir('/tmp'):
  3. print(f)
  1. # import glob
  2. for f in glob.glob('/tmp/*'):
  3. print(f)
  1. # import pathlib
  2. for f in pathlib.Path('/tmp').iterdir():
  3. print(f)

PHP

  1. foreach (glob('/tmp/*') as $f) {
  2. echo $f, "\n";
  3. }

Perl

  1. for (glob '/tmp/*') {
  2. print $_, "\n";
  3. }
  1. print $_, "\n" for glob '/tmp/*'

指定されたディレクトリ配下の全てのファイルのリストを取得する関数

Java

Java 16以降
  1. // import java.io.IOException;
  2. // import java.nio.file.Path;
  3. // import java.util.stream.Stream;
  4. public static List<Path> getAllFiles(Path path) throws IOException {
  5. try (Stream<Path> stream = Files.walk(path)) {
  6. return stream.filter(Files::isRegularFile).toList();
  7. }
  8. }
Java 15まで
  1. // import java.io.IOException;
  2. // import java.nio.file.Path;
  3. // import java.util.stream.*;
  4. public static List<Path> getAllFiles(Path path) throws IOException {
  5. try (Stream<Path> stream = Files.walk(path)) {
  6. return stream.filter(Files::isRegularFile).collect(Collectors.toList());
  7. }
  8. }

Groovy

  1. def getAllFiles(File file) {
  2. file.directory ?
  3. file.listFiles().collect { getAllFiles it }.flatten() :
  4. [file]
  5. }
  1. def getAllFiles(File dir) {
  2. def result = dir.listFiles() as List
  3. dir.eachDirRecurse { subdir ->
  4. subdir.listFiles().each { result << it }
  5. }
  6. result.findAll { it.file }
  7. }
  1. // import java.nio.file.*
  2. // import java.util.stream.Collectors
  3. def getAllFiles(Path path) {
  4. def stream = Files.walk path
  5. try {
  6. stream.filter { Files.isRegularFile(it) }.collect Collectors.toList()
  7. } finally {
  8. stream.close()
  9. }
  10. }
Groovy 3.0以降
  1. // import java.nio.file.*
  2. // import java.util.stream.Collectors
  3. def getAllFiles(Path path) {
  4. try (def stream = Files.walk path) {
  5. stream.filter(Files::isRegularFile).collect Collectors.toList()
  6. }
  7. }

Kotlin

  1. // import java.nio.file.*
  2. // import kotlin.streams.toList
  3. fun getAllFiles(path: Path) = Files.walk(path).use {
  4. it.filter { ! Files.isDirectory(it) }.toList()
  5. }
  1. // import java.io.File
  2. fun getAllFiles(file: File): Sequence<File> {
  3. return file.listFiles().asSequence().flatMap {
  4. if (it.isDirectory) getAllFiles(it) else sequenceOf(it)
  5. }
  6. }

Scala

  1. // import java.io.File
  2. def getAllFiles(file: File): Seq[File] =
  3. if (file.isDirectory) file.listFiles.toSeq.flatMap(getAllFiles) else Seq(file)
  1. // import java.io.File
  2. def getAllFiles(file: File): Seq[File] = file.isDirectory match {
  3. case true => file.listFiles.toSeq.flatMap(getAllFiles)
  4. case false => Seq(file)
  5. }
scala-io を使った場合
  1. // import scalax.file.Path
  2. // import scalax.file.PathMatcher.IsFile
  3. def getAllFiles(dir: Path) = dir ** IsFile

Erlang

  1. get_all_files(Dir) -> filelib:fold_files(Dir, "", true, fun(File, List) -> [File|List] end, []).

Haskell

  1. -- import Directory
  2. -- import IO
  3. getAllFiles dir = do
  4. contents <- catch (getDirectoryContents dir) (\ _ -> return [])
  5. let contents' = [dir ++ "/" ++ path | path <- contents, notElem path [".", ".."]]
  6. contents'' <- mapM getAllFiles contents'
  7. return $ contents' ++ concat contents''

PowerShell

  1. function getAllFiles([System.IO.DirectoryInfo] $dir) {
  2. $dir.GetFiles()
  3. $dir.GetDirectories() | foreach { getAllFiles($_) }
  4. }

F#

  1. // open System.IO
  2. let rec getAllFiles dir = seq {
  3. yield! Directory.EnumerateFiles dir
  4. for subdir in Directory.EnumerateDirectories dir do yield! getAllFiles subdir
  5. }
  1. // open System.IO
  2. let rec getAllFiles (dir : DirectoryInfo) = seq {
  3. yield! dir.EnumerateFiles()
  4. for subdir in dir.EnumerateDirectories() do yield! getAllFiles subdir
  5. }
  1. // open System.IO
  2. let getAllFiles dir =
  3. let generator = function
  4. | [] -> None
  5. | head :: tail ->
  6. let dirs = Directory.EnumerateDirectories head |> Seq.toList
  7. Some(Directory.EnumerateFiles head, List.append dirs tail)
  8. Seq.unfold generator [dir] |> Seq.concat
  1. // open System.IO
  2. let getAllFiles =
  3. let generator dirs = if Seq.isEmpty dirs then None
  4. else Some(dirs, Seq.collect Directory.EnumerateDirectories dirs)
  5. Seq.singleton >> Seq.unfold generator >> Seq.concat >> Seq.collect Directory.EnumerateFiles

C#

  1. // using System.IO;
  2. // using System.Linq;
  3. public static IEnumerable<string> GetAllFiles(string dir) {
  4. return Directory.EnumerateFiles(dir).Concat(
  5. Directory.EnumerateDirectories(dir).SelectMany(GetAllFiles));
  6. }
  1. // using System.IO;
  2. // using System.Linq;
  3. public static IEnumerable<FileInfo> GetAllFiles(DirectoryInfo dir) {
  4. return dir.GetFiles().Concat(
  5. from subDir in dir.GetDirectories()
  6. from file in GetAllFiles(subDir)
  7. select file
  8. );
  9. }

C++

  1. #include <dirent.h>
  2. #include <sstream>
  3. #include <vector>
  4. vector<string> get_all_files(const string& path) {
  5. vector<string> files;
  6. if (DIR* dir = opendir(path.c_str())) {
  7. while (struct dirent* ent = readdir(dir)) {
  8. string name = ent->d_name;
  9. if (name == "." || name == "..") {
  10. continue;
  11. }
  12. stringstream ss;
  13. ss << path << '/' << name;
  14. files.push_back(ss.str());
  15. if (ent->d_type == DT_DIR) {
  16. vector<string> sub_files = get_all_files(ss.str());
  17. for (vector<string>::iterator it = sub_files.begin(); it != sub_files.end(); it++) {
  18. files.push_back(*it);
  19. }
  20. }
  21. }
  22. closedir(dir);
  23. }
  24. return files;
  25. }
Boost を使った場合
  1. #include <vector>
  2. #include <boost/filesystem/operations.hpp>
  3. // using namespace boost::filesystem;
  4. vector<string> get_all_files(const path& dir_path) {
  5. vector<string> files;
  6. recursive_directory_iterator end;
  7. for (recursive_directory_iterator it(dir_path); it != end; it++) {
  8. files.push_back(it->path().string());
  9. }
  10. return files;
  11. }

Go

  1. // import "container/list"
  2. // import "io/ioutil"
  3. // import "os"
  4. func GetAllFiles(dir string) (*list.List, error) {
  5. info, err := os.Stat(dir)
  6. if err != nil { return nil, err }
  7. if info.IsDir() {
  8. files, err := ioutil.ReadDir(dir)
  9. if err != nil { return nil, err }
  10. list1 := list.New()
  11. for _, file := range files {
  12. subdir := fmt.Sprintf("%s/%s", dir, file.Name())
  13. list1.PushBack(subdir)
  14. list2, err := GetAllFiles(subdir)
  15. if err != nil { return nil, err }
  16. list1.PushBackList(list2)
  17. }
  18. return list1, nil
  19. }
  20. return list.New(), nil
  21. }

Rust

  1. // use std::fs;
  2. // use std::path;
  3. pub fn get_all_files(path: &path::Path, files: &mut Vec<String>) {
  4. let entries = fs::read_dir(path).unwrap();
  5. for entry in entries {
  6. let e = entry.unwrap();
  7. let file_type = e.file_type().unwrap();
  8. if file_type.is_dir() {
  9. get_all_files(&e.path(), files);
  10. } else {
  11. files.push(format!("{}", e.path().display()));
  12. }
  13. }
  14. }

TypeScript

  1. // import * as fs from 'fs';
  2. function getAllFiles(dir: string): string[] {
  3. return fs.readdirSync(dir).flatMap(file => {
  4. let path = `${dir}/${file}`;
  5. return fs.statSync(path).isDirectory() ? getAllFiles(path) : path;
  6. });
  7. }

JavaScript

Node.js の場合
  1. // const fs = require('fs');
  2. function getAllFiles(dir) {
  3. return fs.readdirSync(dir).flatMap(file => {
  4. let path = `${dir}/${file}`;
  5. return fs.statSync(path).isDirectory() ? getAllFiles(path) : path;
  6. });
  7. }

CoffeeScript

Node.js の場合
  1. # fs = require 'fs'
  2. getAllFiles = (dir) ->
  3. fs.readdirSync(dir).flatMap (file) ->
  4. path = "#{dir}/#{file}"
  5. if fs.statSync(path).isDirectory() then getAllFiles path else path

Ruby

  1. def get_all_files(dir) # dir は文字列
  2. test('d', dir) ? Dir.glob(dir + '/*').flat_map {|d| get_all_files d } : [dir]
  3. end

Python

  1. # import os
  2. def get_all_files(dir): # dir は文字列
  3. l = []
  4. for dirpath, dirnames, filenames in os.walk(dir): # walk はサブディレクトリを再帰的に辿る関数
  5. l.extend(dirpath + '/' + f for f in filenames)
  6. return l
  1. # import glob
  2. # import os
  3. def get_all_files(dir): # dir は文字列
  4. l = []
  5. if os.path.isdir(dir):
  6. for f in glob.glob(dir + '/*'):
  7. l.extend(get_all_files(f))
  8. else:
  9. l.append(dir)
  10. return l
  1. # import pathlib
  2. def get_all_files(dir): # dir は文字列
  3. return (f for f in pathlib.Path(dir).glob('**/*') if f.is_file())

PHP

  1. function get_all_files($dir, array &$files = NULL) {
  2. if ($files === NULL) {
  3. $files = [];
  4. }
  5. if (($files_in_dir = scandir($dir)) === FALSE) {
  6. $error = error_get_last();
  7. throw new Exception($error['message'] . "; $dir");
  8. }
  9. foreach ($files_in_dir as $file) {
  10. if ($file !== '.' && $file !== '..') {
  11. $file_path = "$dir/$file";
  12. array_push($files, $file_path);
  13. if (is_dir($file_path)) {
  14. get_all_files($file_path, $files);
  15. }
  16. }
  17. }
  18. return $files;
  19. }

Perl

  1. # use File::Find;
  2. sub get_all_files {
  3. my $dir = shift;
  4. my @result;
  5. find sub { push @result, $File::Find::name }, $dir;
  6. @result;
  7. }

テキストファイルの内容を読み出し、行番号を付けて別のファイルに書き出す

Java

1行ずつ読み書き
  1. // import java.io.BufferedWriter;
  2. // import java.nio.file.*;
  3. // import java.util.stream.Stream;
  4. try (Stream<String> lines = Files.lines(Path.of("in.txt"));
  5. BufferedWriter writer = Files.newBufferedWriter(Path.of("out.txt"))) {
  6. int lineNumber = 0;
  7. Iterable<String> iter = lines::iterator;
  8. for (String line : iter) {
  9. writer.write(++lineNumber + " " + line);
  10. writer.newLine();
  11. }
  12. }
先に全部読む
  1. // import java.io.BufferedWriter;
  2. // import java.nio.file.*;
  3. List<String> lines = Files.readAllLines(Path.of("in.txt"));
  4. try (BufferedWriter writer = Files.newBufferedWriter(Path.of("out.txt"))) {
  5. int lineNumber = 0;
  6. for (String line : lines) {
  7. writer.write(++lineNumber + " " + line);
  8. writer.newLine();
  9. }
  10. }

Groovy

1行ずつ読み書き
  1. new File('in.txt').withReader { reader ->
  2. new File('out.txt').withWriter { writer ->
  3. def lineNumber = 0
  4. reader.eachLine { line -> writer.writeLine(++lineNumber + ' ' + line) }
  5. }
  6. }
先に全部読む
  1. def lines = new File('in.txt').readLines()
  2. new File('out.txt').withWriter { writer ->
  3. lines.eachWithIndex { line, i -> writer.writeLine((i + 1) + ' ' + line) }
  4. }

Kotlin

1行ずつ読み書き
  1. // import java.nio.file.*
  2. Files.lines(Path.of("in.txt")).use { lines ->
  3. Files.newBufferedWriter(Path.of("out.txt")).use { writer ->
  4. var lineNumber = 0
  5. for (line in lines) {
  6. writer.write("${++lineNumber} $line")
  7. writer.newLine()
  8. }
  9. }
  10. }
  1. // import java.io.File
  2. File("out.txt").bufferedWriter().use { writer ->
  3. var lineNumber = 0
  4. File("in.txt").forEachLine { line ->
  5. writer.write("${++lineNumber} $line")
  6. writer.newLine()
  7. }
  8. }
  1. // import java.io.File
  2. File("in.txt").bufferedReader().use { reader ->
  3. File("out.txt").bufferedWriter().use { writer ->
  4. for ((i, line) in reader.lineSequence().withIndex()) {
  5. writer.write("${i + 1} $line")
  6. writer.newLine()
  7. }
  8. }
  9. }
先に全部読む
  1. // import java.io.File
  2. val lines = File("in.txt").readLines()
  3. File("out.txt").bufferedWriter().use { writer ->
  4. for ((i, line) in lines.withIndex()) {
  5. writer.write("${i + 1} $line")
  6. writer.newLine()
  7. }
  8. }

Scala

Scala 2.13以降
1行ずつ読み書き
  1. // import java.nio.file._
  2. // import scala.io.Source
  3. // import scala.util.Using
  4. Using(Source fromFile "in.txt") { src =>
  5. Using(Files newBufferedWriter Path.of("out.txt")) { writer =>
  6. for ((line, i) <- src.getLines().zipWithIndex) writer.write("%d %s%n".format(i + 1, line))
  7. }.get
  8. }.get
  1. // import java.nio.file._
  2. // import scala.io.Source
  3. // import scala.util.Using
  4. Using.Manager { use =>
  5. val src = use(Source fromFile "in.txt")
  6. val writer = use(Files newBufferedWriter Path.of("out.txt"))
  7. for ((line, i) <- src.getLines().zipWithIndex) writer.write("%d %s%n".format(i + 1, line))
  8. }.get
scala-io を使った場合
1行ずつ読み書き
  1. // import scalax.file.Path
  2. // import scalax.io.Codec
  3. // import scalax.io.Line.Terminators
  4. implicit val codec = Codec.UTF8
  5. val inLines = Path("in.txt").lines(Terminators.Auto, true)
  6. val outlines = for ((line, i) <- inLines.zipWithIndex) yield "%d %s".format(i + 1, line)
  7. Path("out.txt").writeStrings(outlines)
  1. // import java.io.FileInputStream
  2. // import scalax.file.Path
  3. // import scalax.io.Codec
  4. // import scalax.io.JavaConverters._
  5. // import scalax.io.Line.Terminators
  6. implicit val codec = Codec.UTF8
  7. val inLines = new FileInputStream("in.txt").asInput.lines(Terminators.Auto, true)
  8. Path("out.txt").openOutput { out =>
  9. for ((line, i) <- inLines.zipWithIndex) out.write("%d %s".format(i + 1, line))
  10. }

Erlang

1行ずつ読み書き
  1. fold_lines(File, Fun, AccIn) ->
  2. case io:get_line(File, "") of
  3. eof -> AccIn;
  4. Line -> fold_lines(File, Fun, Fun(Line, AccIn))
  5. end.
  1. {ok, In} = file:open("in.txt", read),
  2. try
  3. {ok, Out} = file:open("out.txt", write),
  4. try
  5. fold_lines(In, fun(Line, LineNumber) ->
  6. io:format(Out, "~b ~s", [LineNumber, Line]),
  7. LineNumber + 1
  8. end, 1)
  9. after
  10. file:close(Out)
  11. end
  12. after
  13. file:close(In)
  14. end.

Haskell

1行ずつ読み書き
  1. -- import Control.Exception
  2. -- import IO hiding (bracket)
  3. bracket (openFile "in.txt" ReadMode) hClose
  4. $ \ inHandle -> do
  5. bracket (openFile "out.txt" WriteMode) hClose
  6. $ \ outHandle -> do
  7. let readWrite lineNumber = IO.catch
  8. (do line <- hGetLine inHandle
  9. hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
  10. readWrite $ lineNumber + 1)
  11. (\ e -> if isEOFError e then return () else ioError e)
  12. readWrite 1
  1. -- import Control.Exception
  2. -- import IO
  3. inHandle <- openFile "in.txt" ReadMode
  4. finally
  5. (do outHandle <- openFile "out.txt" WriteMode
  6. finally
  7. (do let readWrite lineNumber = IO.catch
  8. (do line <- hGetLine inHandle
  9. hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
  10. readWrite $ lineNumber + 1)
  11. (\ e -> if isEOFError e then return () else ioError e)
  12. readWrite 1)
  13. (hClose outHandle))
  14. (hClose inHandle)
先に全部読む
  1. contents <- readFile "in.txt"
  2. writeFile "out.txt" $ unlines $ map f $ zip [1..] $ lines contents where
  3. f (lineNumber, line) = (show lineNumber) ++ " " ++ line
  1. -- import Control.Exception
  2. -- import IO hiding (bracket)
  3. contents <- readFile "in.txt"
  4. bracket (openFile "out.txt" WriteMode) hClose
  5. $ \ outHandle -> do
  6. let write (lineNumber, line) = hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
  7. mapM_ write $ zip [1..] $ lines contents
  1. -- import Control.Exception
  2. -- import IO
  3. contents <- readFile "in.txt"
  4. outHandle <- openFile "out.txt" WriteMode
  5. finally
  6. (do let write (lineNumber, line) = hPutStrLn outHandle $ (show lineNumber) ++ " " ++ line
  7. mapM_ write $ zip [1..] $ lines contents)
  8. (hClose outHandle)
Cabal の MissingH を使った場合
先に全部読む
  1. -- import Control.Exception
  2. -- import IO hiding (bracket)
  3. -- import System.IO.Utils
  4. bracket (openFile "in.txt" ReadMode) hClose
  5. $ \ inHandle -> do
  6. bracket (openFile "out.txt" WriteMode) hClose
  7. $ \ outHandle -> do
  8. lines <- hGetLines inHandle
  9. let f (lineNumber, line) = (show lineNumber) ++ " " ++ line
  10. hPutStrLns outHandle $ map f $ zip [1..] lines
  1. -- import Control.Exception
  2. -- import IO
  3. -- import System.IO.Utils
  4. inHandle <- openFile "in.txt" ReadMode
  5. finally
  6. (do outHandle <- openFile "out.txt" WriteMode
  7. finally
  8. (do lines <- hGetLines inHandle
  9. let f (lineNumber, line) = (show lineNumber) ++ " " ++ line
  10. hPutStrLns outHandle $ map f $ zip [1..] lines)
  11. (hClose outHandle))
  12. (hClose inHandle)

PowerShell

  1. cat in.txt | foreach -Begin { $lineNumber = 0 } { "$(++$lineNumber + 0) $_" } > out.txt
  1. cat in.txt | foreach -Begin { $lineNumber = 0 } { '' + (++$lineNumber) + ' ' + $_ } > out.txt
  1. cat in.txt | foreach -Begin { $lineNumber = 0 } { '{0} {1}' -f ++$lineNumber, $_ } > out.txt

F#

1行ずつ読み書き
  1. // open System.IO
  2. use reader = new StreamReader "in.txt"
  3. use writer = new StreamWriter "out.txt"
  4. let lines = seq { while not reader.EndOfStream do yield reader.ReadLine() }
  5. lines |> Seq.iteri (fun i line -> fprintfn writer "%d %s" (i + 1) line)
  1. // open System.IO
  2. use reader = new StreamReader "in.txt"
  3. use writer = new StreamWriter "out.txt"
  4. let lines = Seq.unfold <| fun (reader : StreamReader) ->
  5. match reader.ReadLine() with
  6. | null -> None
  7. | line -> Some(line, reader)
  8. lines reader |> Seq.iteri (fun i line -> fprintfn writer "%d %s" (i + 1) line)
  1. // open System.IO
  2. use reader = new StreamReader "in.txt"
  3. use writer = new StreamWriter "out.txt"
  4. let mutable lineNumber = 0
  5. while not reader.EndOfStream do
  6. lineNumber <- lineNumber + 1
  7. fprintfn writer "%d %s" lineNumber <| reader.ReadLine()
  1. // open System.IO
  2. use reader = new StreamReader "in.txt"
  3. use writer = new StreamWriter "out.txt"
  4. let generator lineNumber =
  5. match reader.ReadLine() with
  6. | null -> None
  7. | line -> Some(sprintf "%d %s" lineNumber line, lineNumber + 1)
  8. Seq.unfold generator 1 |> Seq.iter writer.WriteLine
  1. // open System.IO
  2. use reader = new StreamReader "in.txt"
  3. use writer = new StreamWriter "out.txt"
  4. let rec readWrite lineNumber = // 1行読んで1行書き出す関数
  5. match reader.ReadLine() with
  6. | null -> () // 読み出せなかったら終了
  7. | line -> // 読み出せたら、それを書き出した後、再帰呼び出し
  8. fprintfn writer "%d %s" lineNumber line
  9. readWrite <| lineNumber + 1
  10. readWrite 1

C#

1行ずつ読み書き
  1. // using System.IO;
  2. using (StreamReader reader = new StreamReader("in.txt")) {
  3. using (StreamWriter writer = new StreamWriter("out.txt")) {
  4. int lineNumber = 0;
  5. string line;
  6. while ((line = reader.ReadLine()) != null) {
  7. writer.WriteLine(++lineNumber + " " + line);
  8. }
  9. }
  10. }
1行ずつ読み書き
C# 8.0以降
  1. // using System.IO;
  2. using var reader = new StreamReader("in.txt");
  3. using var writer = new StreamWriter("out.txt");
  4. int lineNumber = 0;
  5. string line;
  6. while ((line = reader.ReadLine()) != null) {
  7. writer.WriteLine(++lineNumber + " " + line);
  8. }

C++

1行ずつ読み書き
  1. #include <fstream>
  2. ifstream in("in.txt");
  3. if (! in) {
  4. return "cannot open in.txt";
  5. }
  6. ofstream out("out.txt");
  7. if (! out) {
  8. return "cannot open out.txt";
  9. }
  10. const int BUF_SIZE = 1024; // 1行分に十分なサイズ
  11. char buf[BUF_SIZE];
  12. int line_number = 0;
  13. while (! in.eof()) {
  14. in.getline(buf, BUF_SIZE);
  15. if (in.gcount()) {
  16. out << ++line_number << " " << buf << endl;
  17. }
  18. }

Go

1行ずつ読み書き
  1. // import "bufio"
  2. // import "io"
  3. // import "os"
  4. lineNumber := 0
  5. inFile, err := os.Open("in.txt")
  6. if err != nil { return err }
  7. defer inFile.Close()
  8. outFile, err := os.OpenFile("out.txt", os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
  9. if err != nil { return err }
  10. defer outFile.Close()
  11. reader := bufio.NewReader(inFile)
  12. for {
  13. line, err := reader.ReadString('\n') // 次の改行まで読む
  14. if err == io.EOF { break }
  15. if err != nil { return err }
  16. lineNumber++
  17. _, err = fmt.Fprintf(outFile, "%d %s", lineNumber, line)
  18. if err != nil { return err }
  19. }

Rust

  1. // use std::fs;
  2. // use std::io::*;
  3. let reader = BufReader::new(fs::File::open("in.txt").unwrap());
  4. let mut writer = BufWriter::new(fs::File::create("out.txt").unwrap());
  5. let mut index = 0;
  6. for line in reader.lines() {
  7. index += 1;
  8. write!(writer, "{index} {}\n", line.unwrap()).unwrap();
  9. }

TypeScript

Node.js の場合
1行ずつ読み書き
  1. // import * as fs from 'fs';
  2. // import * as readline from 'readline';
  3. let input = fs.createReadStream('in.txt', 'utf8');
  4. try {
  5. let output = fs.createWriteStream('out.txt', 'utf8');
  6. try {
  7. await new Promise(resolve => {
  8. let i = 0;
  9. let reader = readline.createInterface({ input });
  10. reader.on('line', line => output.write(`${++i} ${line}\n`));
  11. reader.on('close', resolve);
  12. });
  13. } finally {
  14. output.close();
  15. }
  16. } finally {
  17. input.close();
  18. }
Node.js の場合
先に全部読む
  1. // import * as fs from 'fs';
  2. // import * as util from 'util';
  3. let content = await util.promisify(fs.readFile)('in.txt', 'utf8');
  4. let lines = content.split(/\n/);
  5. if (lines[lines.length - 1] === '') {
  6. lines.pop();
  7. }
  8. let output = fs.createWriteStream('out.txt', 'utf8');
  9. try {
  10. for (let i = 0; i < lines.length; i++) {
  11. output.write(`${i + 1} ${lines[i]}\n`);
  12. }
  13. } finally {
  14. output.close();
  15. }

JavaScript

Node.js の場合
1行ずつ読み書き
  1. // const fs = require('fs');
  2. // const readline = require('readline');
  3. let input = fs.createReadStream('in.txt', 'utf8');
  4. try {
  5. let output = fs.createWriteStream('out.txt', 'utf8');
  6. try {
  7. await new Promise(resolve => {
  8. let i = 0;
  9. let reader = readline.createInterface({ input });
  10. reader.on('line', line => output.write(`${++i} ${line}\n`));
  11. reader.on('close', resolve);
  12. });
  13. } finally {
  14. output.close();
  15. }
  16. } finally {
  17. input.close();
  18. }
Node.js の場合
先に全部読む
  1. // const fs = require('fs');
  2. // const util = require('util');
  3. let content = await util.promisify(fs.readFile)('in.txt', 'utf8');
  4. let lines = content.split(/\n/);
  5. if (lines[lines.length - 1] === '') {
  6. lines.pop();
  7. }
  8. let output = fs.createWriteStream('out.txt', 'utf8');
  9. try {
  10. for (let i = 0; i < lines.length; i++) {
  11. output.write(`${i + 1} ${lines[i]}\n`);
  12. }
  13. } finally {
  14. output.close();
  15. }

CoffeeScript

Node.js の場合
1行ずつ読み書き
  1. # fs = require 'fs'
  2. # readline = require 'readline'
  3. input = fs.createReadStream 'in.txt', 'utf8'
  4. try
  5. output = fs.createWriteStream 'out.txt', 'utf8'
  6. try
  7. await new Promise (resolve) ->
  8. i = 0
  9. reader = readline.createInterface { input }
  10. reader.on 'line', (line) -> output.write "#{++i} #{line}\n"
  11. reader.on 'close', resolve
  12. finally
  13. output.close()
  14. finally
  15. input.close()
Node.js の場合
先に全部読む
  1. # fs = require 'fs'
  2. # util = require 'util'
  3. content = await util.promisify(fs.readFile) 'in.txt', 'utf8'
  4. lines = content.split /\n/
  5. lines.pop() if lines[lines.length - 1] == ''
  6. output = fs.createWriteStream 'out.txt', 'utf8'
  7. try
  8. output.write "#{i + 1} #{lines[i]}\n" for i in [0...lines.length]
  9. finally
  10. output.close()

Ruby

1行ずつ読み書き
  1. open 'in.txt', 'r' do |in_file|
  2. open 'out.txt', 'w' do |out_file|
  3. in_file.each {|line| out_file << in_file.lineno << ' ' << line }
  4. end
  5. end
  1. open 'out.txt', 'w' do |out_file|
  2. lineno = 0
  3. File.foreach 'in.txt' do |line|
  4. lineno += 1
  5. out_file << lineno << ' ' << line
  6. end
  7. end
先に全部読む
  1. lines = IO.readlines 'in.txt'
  2. open 'out.txt', 'w' do |out_file|
  3. lines.each_with_index {|line, i| out_file << (i + 1) << ' ' << line }
  4. end

Python

1行ずつ読み書き
  1. with open('in.txt', 'r') as in_file:
  2. with open('out.txt', 'w') as out_file:
  3. for i, line in enumerate(in_file):
  4. out_file.write('%d %s' % (i + 1, line))
  1. with open('in.txt', 'r') as in_file:
  2. with open('out.txt', 'w') as out_file:
  3. for i, line in enumerate(in_file):
  4. out_file.write(str(i + 1) + ' ' + line)
  1. with open('in.txt', 'r') as in_file:
  2. with open('out.txt', 'w') as out_file:
  3. for i, line in enumerate(in_file):
  4. print(i + 1, line, end = '', file = out_file)
  1. # import fileinput
  2. in_file = fileinput.input('in.txt')
  3. try:
  4. with open('out.txt', 'w') as out_file:
  5. for line in in_file:
  6. out_file.write('%d %s' % (in_file.lineno(), line))
  7. finally:
  8. in_file.close()
  1. # import contextlib
  2. # import fileinput
  3. with contextlib.closing(fileinput.input('in.txt')) as in_file:
  4. with open('out.txt', 'w') as out_file:
  5. for line in in_file:
  6. out_file.write('%d %s' % (in_file.lineno(), line))
先に全部読む
  1. with open('in.txt', 'r') as in_file:
  2. lines = in_file.readlines()
  3. with open('out.txt', 'w') as out_file:
  4. for i, line in enumerate(lines):
  5. out_file.write(str(i + 1) + ' ' + line)
  1. with open('in.txt', 'r') as in_file:
  2. lines = in_file.readlines()
  3. with open('out.txt', 'w') as out_file:
  4. for i, line in enumerate(lines):
  5. print(i + 1, line, end = '', file = out_file)

PHP

先に全部読む
  1. if (($lines = file('in.txt')) === FALSE) {
  2. $error = error_get_last();
  3. throw new Exception($error['message']);
  4. }
  5. foreach ($lines as $i => &$line) {
  6. $line = ($i + 1) . ' ' . $line;
  7. }
  8. if (file_put_contents('out.txt', $lines) === FALSE) {
  9. $error = error_get_last();
  10. throw new Exception($error['message']);
  11. }

Perl

Perl 5.6以降での基本形

1行ずつ読み書き
  1. open my $in, 'in.txt' or die "Cannot open in.txt; $!";
  2. open my $out, '> out.txt' or die "Cannot open out.txt; $!";
  3. print $out "$. $_" while <$in>;
  4. # close は暗黙的に行われる
  1. open my $in, '<', 'in.txt' or die "Cannot open in.txt; $!";
  2. open my $out, '>', 'out.txt' or die "Cannot open out.txt; $!";
  3. printf {$out} '%d %s', $., $_ while <$in>;
  4. # close は暗黙的に行われる
先に全部読む
  1. open my $in, 'in.txt' or die "Cannot open in.txt; $!";
  2. open my $out, '> out.txt' or die "Cannot open out.txt; $!";
  3. my @lines = <$in>;
  4. printf $out '%d %s', $_ + 1, $lines[$_] for 0..$#lines;
  5. # close は暗黙的に行われる

オブジェクト指向での書き方

1行ずつ読み書き
  1. # use IO::File;
  2. my $in = IO::File->new('in.txt', 'r') or die "Cannot open in.txt; $!";
  3. my $out = IO::File->new('out.txt', 'w') or die "Cannot open out.txt; $!";
  4. $out->print($in->input_line_number, " $_") while <$in>;
  5. # close は暗黙的に行われる
  1. # use IO::File;
  2. my $in = IO::File->new('in.txt', O_RDONLY) or die "Cannot open in.txt; $!";
  3. my $out = IO::File->new('out.txt', O_WRONLY | O_CREAT) or die "Cannot open out.txt; $!";
  4. $out->printf('%d %s', $in->input_line_number, $_) while defined($_ = $in->getline);
  5. # close は暗黙的に行われる
先に全部読む
  1. # use IO::File;
  2. my $in = IO::File->new('in.txt', 'r') or die "Cannot open in.txt; $!";
  3. my $out = IO::File->new('out.txt', 'w') or die "Cannot open out.txt; $!";
  4. my @lines = $in->getlines;
  5. $out->printf('%d %s', $_ + 1, $lines[$_]) for 0..$#lines;
  6. # close は暗黙的に行われる

CSVファイルを読み込み、1列目の数値の昇順で別のファイルに出力する

Java

Commons Text を使った場合
  1. // import java.io.*;
  2. // import java.nio.file.*;
  3. // import java.util.stream.Collectors;
  4. // import java.util.stream.Stream;
  5. // import org.apache.commons.text.*;
  6. List<List<String>> rows;
  7. StrTokenizer tokenizer = StringTokenizer.getCSVInstance();
  8. try (Stream<String> lines = Files.lines(Path.of("in.csv"))) {
  9. rows = lines.map(line -> tokenizer.reset(line).getTokenList()).collect(Collectors.toList());
  10. }
  11. Collections.sort(rows, Comparator.comparing(row -> Double.parseDouble(row.get(0))));
  12. try (BufferedWriter writer = new BufferedWriter(new FileWriter("out.csv"))) {
  13. for (List<String> row : rows) {
  14. writer.write(row.stream().map(StringEscapeUtils::escapeCsv).collect(Collectors.joining(",")));
  15. writer.newLine();
  16. }
  17. }
opencsv を使った場合
  1. // import java.io.*;
  2. // import com.opencsv.*;
  3. List<String[]> rows;
  4. try (CSVReader reader = new CSVReader(new FileReader("in.csv"))) {
  5. rows = reader.readAll();
  6. }
  7. Collections.sort(rows, Comparator.comparing(row -> Double.parseDouble(row[0])));
  8. try (CSVWriter writer = new CSVWriter(new FileWriter("out.csv"))) {
  9. writer.writeAll(rows);
  10. }

Groovy

Commons Text を使った場合
  1. // import org.apache.commons.text.*
  2. def tokenizer = StringTokenizer.CSVInstance
  3. def tokenize = { tokenizer.reset(it).toList() }
  4. def rows = new File('in.csv').readLines().collect { tokenize it }
  5. rows = rows.sort { it[0] as double }
  6. new File('out.csv').withWriter { writer ->
  7. for (row in rows) {
  8. row = row.collect(StringEscapeUtils.&escapeCsv)
  9. writer.writeLine row.join(',')
  10. }
  11. }
opencsv を使った場合
  1. // import com.opencsv.*
  2. def rows = new File('in.csv').withReader { new CSVReader(it).readAll() }
  3. rows = rows.sort { it[0] as double }
  4. new File('out.csv').withWriter { new CSVWriter(it).writeAll rows }

Kotlin

Commons Text を使った場合
  1. // import java.io.File
  2. // import org.apache.commons.text.*
  3. val tokenizer = StringTokenizer.getCSVInstance()
  4. val lines = File("in.csv").readLines()
  5. val rows = lines.map { tokenizer.reset(it).getTokenList() }
  6. File("out.csv").bufferedWriter().use { writer ->
  7. for (row in rows.sortedBy { it[0].toBigDecimal() }) {
  8. writer.write(row.map(StringEscapeUtils::escapeCsv).joinToString(","))
  9. writer.newLine()
  10. }
  11. }
opencsv を使った場合
  1. // import java.io.*
  2. // import com.opencsv.*
  3. val rows = CSVReader(FileReader("in.csv")).use { it.readAll() }
  4. CSVWriter(FileWriter("out.csv")).use {
  5. it.writeAll(rows.sortedBy { it[0].toBigDecimal() })
  6. }

Scala

Scala 2.13以降
Commons Text を使った場合
  1. // import java.io._
  2. // import scala.io.Source
  3. // import scala.jdk.javaapi.CollectionConverters.asScala
  4. // import scala.util.Using
  5. // import org.apache.commons.text._
  6. val tokenizer = StringTokenizer.getCSVInstance
  7. def tokenize(s: String) = asScala(tokenizer reset s).toList
  8. val rows = Using(Source fromFile "in.csv") { _.getLines().map(tokenize).toList }.get // rows の型は List[List[String]]
  9. Using(new BufferedWriter(new FileWriter("out.csv"))) { writer =>
  10. for (row <- rows.sortBy(_(0).toDouble)) {
  11. writer.write(row.map(StringEscapeUtils.escapeCsv) mkString ",")
  12. writer.newLine
  13. }
  14. }.get
Scala 2.13以降
opencsv を使った場合
  1. // import java.io._
  2. // import scala.jdk.javaapi.CollectionConverters.asScala
  3. // import scala.util.Using
  4. // import com.opencsv._
  5. val rows = Using(new CSVReader(new FileReader("in.csv"))) { reader => asScala(reader.readAll) }.get
  6. Using(new CSVWriter(new FileWriter("out.csv"))) { writer =>
  7. rows.sortBy(_(0).toDouble).foreach(writer.writeNext _)
  8. }.get

Haskell

Cabal の csv を使った場合
  1. -- import List
  2. -- import Numeric
  3. -- import Text.CSV
  4. Right table <- parseCSVFromFile "in.csv"
  5. let table' = sortBy (\ rec1 rec2 -> compare (f rec1) (f rec2)) table where
  6. f (cell0 : _) = case cell0 of
  7. '-' : s -> - (strToFloat s)
  8. s -> strToFloat s
  9. strToFloat s = case readFloat s of
  10. [(float, "")] -> float
  11. writeFile "out.csv" $ printCSV table'

PowerShell

  1. cat in.csv | ConvertFrom-CSV -Header @(1..9) | sort { [double] $_.'1' } | ConvertTo-CSV | select -Index @(2..9999) > out.csv
  2. # 9 のところには列数の最大値、9999 のところには行数の最大値を指定する必要がある

F#

  1. // open System.IO
  2. // open Microsoft.VisualBasic.FileIO
  3. let read() = // string の配列のリストを返す関数
  4. use parser = new TextFieldParser("in.csv", Delimiters = [|","|])
  5. [while not parser.EndOfData do yield parser.ReadFields()]
  6. let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
  7. let rowToString = Seq.map quote >> String.concat "," // string の配列を引数に取り、string を返す関数
  8. let write (lines : seq<string>) =
  9. use writer = new StreamWriter "out.csv"
  10. lines |> Seq.iter writer.WriteLine
  11. read() |> List.sortBy (fun row -> double row.[0]) |> Seq.map rowToString |> write
  1. // open System.IO
  2. // open Microsoft.VisualBasic.FileIO
  3. let rows = using (new TextFieldParser("in.csv", Delimiters = [|","|])) // rows の型は、string の配列のリスト
  4. (fun parser -> [while not parser.EndOfData do yield parser.ReadFields()])
  5. let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
  6. let rowToString = Seq.map quote >> String.concat "," // string の配列を引数に取り、string を返す関数
  7. let lines = rows |> List.sortBy (fun row -> double row.[0]) |> Seq.map rowToString
  8. using (new StreamWriter "out.csv")
  9. (fun writer -> lines |> Seq.iter writer.WriteLine)
  1. // open System.IO
  2. // open Microsoft.VisualBasic.FileIO
  3. let rows = using (new TextFieldParser("in.csv", Delimiters = [|","|]))
  4. (fun parser -> [while not parser.EndOfData do yield parser.ReadFields()]) // rows の型は、string の配列のリスト
  5. let quote (s : string) = s.Replace("\"", "\"\"") |> sprintf "\"%s\""
  6. using (new StreamWriter "out.csv")
  7. (fun writer ->
  8. for row in rows |> List.sortBy (fun row -> double row.[0]) do
  9. row |> Seq.map quote |> String.concat "," |> writer.WriteLine
  10. )
CSV I/Oライブラリ.NET を使った場合
  1. // open System.IO
  2. // open Uguu.IO.Csv
  3. let rows = using (new CsvReader(new StreamReader "in.csv"))
  4. (fun reader ->
  5. let getRow() = Array.init reader.FieldCount (fun i -> reader.[i]) // string の配列を返す関数
  6. [while reader.Read() do yield getRow()] // rows の型は、string の配列のリスト
  7. )
  8. using (new CsvWriter(new StreamWriter "out.csv"))
  9. (fun writer ->
  10. for row in rows |> List.sortBy (fun row -> double row.[0]) do
  11. writer.Write row
  12. writer.WriteNewLine()
  13. )

C#

  1. // using System.IO;
  2. // using System.Linq;
  3. // using Microsoft.VisualBasic.FileIO;
  4. var rows = new List<string[]>();
  5. using (var parser = new TextFieldParser("in.csv")) {
  6. parser.Delimiters = new string[] { "," };
  7. while (! parser.EndOfData) {
  8. rows.Add(parser.ReadFields());
  9. }
  10. }
  11. Func<string, string> quote = (s) => '"' + s.Replace("\"", "\"\"") + '"';
  12. Func<string[], string> rowToString = (row) => row.Select(quote).Aggregate((x, y) => x + ',' + y);
  13. var lines = from row in rows orderby double.Parse(row[0]) select rowToString(row);
  14. using (var writer = new StreamWriter("out.csv")) {
  15. foreach (var line in lines) {
  16. writer.WriteLine(line);
  17. }
  18. }
CSV I/Oライブラリ.NET を使った場合
  1. // using System.IO;
  2. // using System.Linq;
  3. // using Uguu.IO.Csv;
  4. var rows = new List<string[]>();
  5. using (var reader = new CsvReader(new StreamReader("in.csv"))) {
  6. while (reader.Read()) {
  7. var row = new string[reader.FieldCount];
  8. for (var i = 0; i < row.Length; i++) {
  9. row[i] = reader[i];
  10. }
  11. rows.Add(row);
  12. }
  13. }
  14. using (var writer = new CsvWriter(new StreamWriter("out.csv"))) {
  15. foreach (var row in rows.OrderBy(row => double.Parse(row[0]))) {
  16. writer.Write(row);
  17. writer.WriteNewLine();
  18. }
  19. }

Go

  1. // インターフェース sort.Interface を実装する
  2. type FirstNumAscending [][]string
  3. func (this FirstNumAscending) Len() int {
  4. return len(this)
  5. }
  6. func (this FirstNumAscending) Less(i, j int) bool {
  7. ni, _ := strconv.Atoi(this[i][0])
  8. nj, _ := strconv.Atoi(this[j][0])
  9. return ni < nj
  10. }
  11. func (this FirstNumAscending) Swap(i, j int) {
  12. this[i], this[j] = this[j], this[i]
  13. }
  1. // import "encoding/csv"
  2. // import "os"
  3. // import "sort"
  4. // import "strconv"
  5. inFile, err := os.Open("in.csv")
  6. if err != nil { return err }
  7. defer inFile.Close()
  8. reader := csv.NewReader(inFile)
  9. rows, err := reader.ReadAll()
  10. if err != nil { return err }
  11. sort.Sort(FirstNumAscending(rows))
  12. outFile, err := os.OpenFile("out.csv", os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
  13. if err != nil { return err }
  14. defer outFile.Close()
  15. writer := csv.NewWriter(outFile)
  16. writer.WriteAll(rows)

Rust

csv を使った場合
  1. // use csv;
  2. let mut reader = csv::ReaderBuilder::new().has_headers(false).from_path("in.csv").unwrap();
  3. let mut writer = csv::Writer::from_path("out.csv").unwrap();
  4. let it = reader.records().map(|r| {
  5. let record = r.unwrap();
  6. let n: i32 = record[0].parse().unwrap();
  7. (n, record)
  8. });
  9. let mut vec: Vec<_> = it.collect();
  10. vec.sort_by_key(|&(n, _)| n);
  11. for (_, record) in vec {
  12. writer.write_record(record.iter()).unwrap();
  13. }

Ruby

  1. # require 'csv'
  2. rows = CSV.readlines('in.csv', :converters => :numeric).sort_by {|row| row[0] } # :numeric は文字列から数値に変換するオプション
  3. CSV.open 'out.csv', 'w' do |writer|
  4. rows.each {|row| writer << row }
  5. end

Python

  1. # import csv
  2. with open('in.csv', 'r') as f:
  3. rows = list(csv.reader(f))
  4. rows.sort(key = lambda row: float(row[0]))
  5. with open('out.csv', 'w') as f:
  6. csv.writer(f, lineterminator = '\n').writerows(rows)

PHP

  1. if (($f = fopen('in.csv', 'r')) === FALSE) {
  2. $error = error_get_last();
  3. throw new Exception($error['message']);
  4. }
  5. $rows = [];
  6. while (($row = fgetcsv($f)) !== FALSE) {
  7. array_push($rows, $row);
  8. }
  9. fclose($f);
  10. usort($rows, function($a, $b) { return (float)$a[0] - (float)$b[0]; });
  11. if (($f = fopen('out.csv', 'w')) === FALSE) {
  12. $error = error_get_last();
  13. throw new Exception($error['message']);
  14. }
  15. foreach ($rows as $row) {
  16. if (fputcsv($f, $row) === FALSE) {
  17. $error = error_get_last();
  18. fclose($f);
  19. throw new Exception($error['message'] . '; out.csv');
  20. }
  21. }
  22. fclose($f);

Perl

CPAN の Text::CSV を使った場合
  1. # use Text::CSV;
  2. open my $in, 'in.csv' or die "Cannot open in.csv; $!";
  3. open my $out, '> out.csv' or die "Cannot open out.csv; $!";
  4. my $csv = Text::CSV->new;
  5. my @rows;
  6. push @rows, $_ while $_ = $csv->getline($in);
  7. $csv->eol($/);
  8. $csv->print($out, $_) for sort { $a->[0] <=> $b->[0] } @rows;

CSVのパーサを自作する

Groovy

  1. class CsvParser {
  2. private def sb
  3. private def lastMatch
  4. def CsvParser(input) {
  5. sb = new StringBuilder(input)
  6. }
  7. private def parse(regex) {
  8. lastMatch = sb =~ "^(?:$regex)"
  9. if (lastMatch.find()) {
  10. def result = lastMatch.group()
  11. sb.delete 0, result.length()
  12. result
  13. }
  14. }
  15. private def parseList(separator, closure) {
  16. def result = []
  17. for (;;) {
  18. result << closure()
  19. if (! parse(separator)) break
  20. }
  21. result
  22. }
  23. private def parseCell() { // セルのパース
  24. if (parse('"((""|[^"])*)"')) { // ダブルクォートで括られている場合
  25. lastMatch.group(1).replace '""', '"'
  26. } else { // ダブルクォートで括られていない場合
  27. parse '[^",\r\n]*'
  28. }
  29. }
  30. def parseRow() { // レコードのパース
  31. parseList ',', this.&parseCell
  32. }
  33. def parseTable() { // テーブルのパース
  34. parseList '\r\n?|\n', this.&parseRow
  35. }
  36. }
  1. def csv = new File('in.csv').withReader { it.text }
  2. def table = new CsvParser(csv).parseTable()

Scala

  1. // import scala.util.parsing.combinator.RegexParsers
  2. class CsvParser extends RegexParsers {
  3. override def skipWhitespace = false
  4. private val q = "\"" // ダブルクォート
  5. private val ln = """\r\n?|\n""".r // 改行
  6. private val quotedCell = q ~> """([^"]|"")*""".r <~ q ^^ { _.replace(q + q, q) } // ダブルクォートで括られている場合
  7. private val nonQuotedCell = """[^",\r\n]*""".r // ダブルクォートで括られていない場合
  8. private val cell = quotedCell | nonQuotedCell // セルは、ダブルクォートで括られているか括られていないかのいずれか
  9. private val row = repsep(cell, ",") // レコードは、カンマで区切られたセルの集まり
  10. private val table = repsep(row, ln) // テーブルは、改行で区切られたレコードの集まり
  11. def parseRow (in: CharSequence) = parseAll(row, in)
  12. def parseTable(in: CharSequence) = parseAll(table, in)
  13. }
  1. // import scala.io.Source
  2. val src = Source fromFile "in.csv"
  3. val csv = try src.mkString finally src.close
  4. val table = new CsvParser parseTable csv get // 右辺は「new CsvParser.parseTable(csv).get」と同じ

Erlang

  1. parse(Input, Items) -> %% Items のいずれかの文字列をパースする関数
  2. case Items of
  3. [H|T] ->
  4. HasPrefix = lists:prefix(H, Input),
  5. if
  6. HasPrefix -> {H, lists:nthtail(length(H), Input)}; %% H と一致した部分と、それ以降の部分とに分ける
  7. true -> parse(Input, T) %% 再帰呼び出し
  8. end;
  9. [] -> {[], Input}
  10. end.
  11. parse_list(List, Input, Fun, Separators) -> %% Separators で区切られた文字列を Fun でパースして List にまとめる関数
  12. {Item, Input2} = Fun(Input),
  13. case parse(Input2, Separators) of
  14. {[], Input3} -> {lists:reverse([Item|List]), Input3};
  15. {_, Input3} -> parse_list([Item|List], Input3, Fun, Separators)
  16. end.
  17. parse_table(Input) -> parse_list([], Input, fun parse_row/1, ["\r\n", "\r", "\n"]). %% テーブルは、改行で区切られたレコードの集まり
  18. parse_row(Input) -> parse_list([], Input, fun parse_cell/1, [","]). %% レコードは、カンマで区切られたセルの集まり
  19. parse_cell([$"|T]) -> parse_quoted_cell([], T); %% セルは、ダブルクォートで括られているか、
  20. parse_cell(Input) -> parse_non_quoted_cell([], Input). %% 括られていないかのいずれか
  21. parse_quoted_cell(S, [$", $"|T]) -> parse_quoted_cell([$"|S], T); %% ダブルクォートで括られたセルをパースする関数
  22. parse_quoted_cell(S, [$"|T]) -> {lists:reverse(S), T};
  23. parse_quoted_cell(S, [H|T]) -> parse_quoted_cell([H|S], T).
  24. parse_non_quoted_cell(S, [H|T]) -> %% ダブルクォートで括られていないセルをパースする関数
  25. IsMember = lists:member(H, [$,, $", $\r, $\n]),
  26. if
  27. IsMember -> {lists:reverse(S), [H|T]};
  28. true -> parse_non_quoted_cell([H|S], T)
  29. end;
  30. parse_non_quoted_cell(S, []) -> {lists:reverse(S), []}.
  1. {ok, Bin} = file:read_file("in.csv"),
  2. Input = binary_to_list(Bin),
  3. {Result, []} = parse_table(Input).

Haskell

  1. -- import Text.ParserCombinators.ReadP
  2. quotedCell = do -- ダブルクォートで括られている場合
  3. char '"'
  4. contents <- many $ string "\"\"" +++ munch1 (/= '"')
  5. char '"'
  6. return $ concat $ map unescape contents
  7. where unescape "\"\"" = "\""
  8. unescape s = s
  9. nonQuotedCell = munch (\ c -> notElem c "\",\r\n") -- ダブルクォートで括られていない場合
  10. cell = quotedCell +++ nonQuotedCell -- セルは、ダブルクォートで括られているか括られていないかのいずれか
  11. row = cell `sepBy` char ',' -- レコードは、改行で区切られたレコードの集まり
  12. table = row `sepBy` (string "\r" +++ string "\n" +++ string "\r\n") -- テーブルは、改行で区切られたレコードの集まり
  13. parse parser = fst . head . readP_to_S (do p <- parser; eof; return p)
  1. contents <- readFile "in.csv"
  2. let table' = parse table contents
Cabal の MissingHparsec を使った場合
  1. -- import Data.Either.Utils
  2. -- import Data.String.Utils
  3. -- import Text.ParserCombinators.Parsec
  4. quotedCell = do -- ダブルクォートで括られている場合
  5. segments <- many1
  6. (do char '"'
  7. content <- option "" $ many1 $ noneOf "\""
  8. char '"'
  9. return content)
  10. return $ join "\"" segments
  11. nonQuotedCell = option "" $ many1 $ noneOf "\",\r\n" -- ダブルクォートで括られていない場合
  12. cell = quotedCell <|> nonQuotedCell -- セルは、ダブルクォートで括られているか括られていないかのいずれか
  13. row = cell `sepBy` char ',' -- レコードは、改行で区切られたレコードの集まり
  14. table = row `sepBy` (string "\r" <|> string "\n" <|> string "\r\n") -- テーブルは、改行で区切られたレコードの集まり
  15. parse' parser = forceEither . parse (do p <- parser; eof; return p) ""
  1. contents <- readFile "in.csv"
  2. let table' = parse' table contents

F#

  1. // open System.Text
  2. // open System.Text.RegularExpressions
  3. type CsvParser(input : string) =
  4. let sb = new StringBuilder(input)
  5. let parse pattern =
  6. let m = Regex.Match(string sb, sprintf "^(?:%s)" pattern)
  7. match m.Success with
  8. | true -> sb.Remove(0, m.Value.Length) |> ignore
  9. Some m
  10. | false -> None
  11. let (|Parse|_|) pattern _ = parse pattern
  12. let parseList separator (parseItem : unit -> Option<'a>) =
  13. Some [
  14. let _continue = ref true
  15. while !_continue do
  16. match parseItem() with
  17. | Some a -> yield a
  18. | None -> ()
  19. match parse separator with
  20. | Some _ -> ()
  21. | None -> _continue := false
  22. ]
  23. let parseCell() = // セルの定義
  24. match () with
  25. | Parse @"""((""""|[^""])*)""" m -> Some(m.Groups.[1].Value.Replace(@"""""", @"""")) // ダブルクォートで括られている場合
  26. | Parse @"[^"",\r\n]*" m -> Some m.Value // ダブルクォートで括られていない場合
  27. | _ -> None
  28. member this.ParseRow() = parseList "," parseCell // レコードは、カンマで区切られたセルの集まり
  29. member this.ParseTable() = parseList @"\r\n?|\n" this.ParseRow // テーブルは、改行で区切られたレコードの集まり
  1. // open System.IO
  2. let csv = using (new StreamReader("in.csv")) (fun reader -> reader.ReadToEnd())
  3. let table = (new CsvParser(csv)).ParseTable().Value

Ruby

  1. # require 'strscan'
  2. class CsvParser
  3. def initialize input
  4. @ss = StringScanner.new input
  5. end
  6. def parse_cell # セルのパース
  7. case
  8. when @ss.scan(/"(([^"]|"")*)"/) ; @ss[1].gsub(/""/, '"') # ダブルクォートで括られている場合
  9. when @ss.scan(/[^",\r\n]*/) ; @ss[0] # ダブルクォートで括られていない場合
  10. end
  11. end
  12. def parse_row # レコードのパース
  13. parse_list(/,/) { parse_cell } # カンマで区切られたセルの集まり
  14. end
  15. def parse_table # テーブルのパース
  16. parse_list(/\r\n?|\n/) { parse_row } # 改行で区切られたレコードの集まり
  17. end
  18. private
  19. def parse_list separator, &block
  20. result = []
  21. begin result << block.call end while @ss.scan separator
  22. result
  23. end
  24. end
  1. table = open 'in.csv' do |file|
  2. CsvParser.new(file.read).parse_table
  3. end
rparsec を使った場合
  1. # require 'rparsec'
  2. class CsvParser
  3. extend RParsec::Parsers
  4. extend RParsec::Functors
  5. QUOTED_CELL = ( # ダブルクォートで括られているセル
  6. char('"') >> (not_char('"') | str('""')).many_.fragment << char('"')
  7. ).map {|s| s.gsub /""/, '"' }
  8. NON_QUOTED_CELL = not_among('"', ',', "\r", "\n").many_.fragment # ダブルクォートで括られていないセル
  9. CELL = QUOTED_CELL | NON_QUOTED_CELL
  10. ROW = CELL.delimited char(',') # レコードは、カンマで区切られたセルの集まり
  11. TABLE = ROW.delimited(str("\r\n") | str("\r") | str("\n")) # テーブルは、改行で区切られたレコードの集まり
  12. end
  1. table = CsvParser::TABLE.parse(File.read 'in.csv')

読み込んだファイルのMD5値を求め、16進の文字列で表す

Java

  1. // import java.io.FileInputStream;
  2. // import java.security.MessageDigest;
  3. MessageDigest md = MessageDigest.getInstance("MD5");
  4. try (FileInputStream stream = new FileInputStream("in.txt")) {
  5. byte[] bytes = new byte[1024];
  6. int length;
  7. while ((length = stream.read(bytes)) > 0) {
  8. md.update(bytes, 0, length);
  9. }
  10. }
  11. Formatter formatter = new Formatter();
  12. for (byte b : md.digest()) {
  13. formatter.format("%02x", b);
  14. }
  15. String hash = formatter.toString();
  1. // import java.nio.file.*;
  2. // import java.security.MessageDigest;
  3. byte[] fileBytes = Files.readAllBytes(Path.of("in.txt"));
  4. byte[] hashBytes = MessageDigest.getInstance("MD5").digest(fileBytes)
  5. Formatter formatter = new Formatter();
  6. for (byte b : hashBytes) {
  7. formatter.format("%02x", b);
  8. }
  9. String hash = formatter.toString();

Groovy

  1. // import java.security.MessageDigest
  2. def fileBytes = new File('in.txt').readBytes()
  3. def hashBytes = MessageDigest.getInstance('MD5').digest(fileBytes)
  4. def hash = hashBytes.collect { String.format '%02x', it }.join()

Kotlin

  1. // import java.io.File
  2. // import java.security.MessageDigest
  3. val md = MessageDigest.getInstance("MD5")
  4. File("in.txt").forEachBlock { buf, length -> md.update(buf, 0, length) }
  5. val hash = md.digest().map("%02x"::format).joinToString("")

Scala

  1. // import java.io.FileInputStream
  2. // import java.security.MessageDigest
  3. val md = MessageDigest.getInstance("MD5")
  4. val stream = new FileInputStream("in.txt")
  5. try {
  6. val bytes = new Array[Byte](1024)
  7. var eof = false
  8. while (! eof) {
  9. val length = stream.read(bytes)
  10. if (length > 0) md.update(bytes, 0, length) else { eof = true }
  11. }
  12. } finally {
  13. stream.close
  14. }
  15. val hash = md.digest.map("%02x".format(_)).mkString
Scala 3.0以降
  1. // import java.io.FileInputStream
  2. // import java.security.MessageDigest
  3. val md = MessageDigest.getInstance("MD5")
  4. val stream = FileInputStream("in.txt")
  5. try
  6. val bytes = new Array[Byte](1024)
  7. var eof = false
  8. while ! eof do
  9. val length = stream.read(bytes)
  10. if length > 0 then md.update(bytes, 0, length) else eof = true
  11. finally
  12. stream.close
  13. val hash = md.digest.map("%02x".format(_)).mkString
java.io.InputStream をラップしたクラスを使った場合
  1. // import java.io._
  2. class BytesIterator(in: InputStream, bufSize: Int = 1024 * 8) extends Iterator[(Array[Byte], Int)] with Closeable {
  3. private val buf = new Array[Byte](bufSize)
  4. private var readSize = 0
  5. def this(file: File) = this(new FileInputStream(file))
  6. override def hasNext = { readSize = in.read(buf); readSize > 0 }
  7. override def next = (buf, readSize)
  8. override def close { in.close }
  9. }
  1. // import java.security.MessageDigest
  2. val md = MessageDigest.getInstance("MD5")
  3. val bytesIter = new BytesIterator(new File("in.txt"))
  4. try {
  5. for ((bytes, length) <- bytesIter) md.update(bytes, 0, length)
  6. } finally {
  7. bytesIter.close
  8. }
  9. val hash = md.digest.map("%02x".format(_)).mkString

Erlang

  1. {ok, Binary} = file:read_file("in.txt"),
  2. Digest = erlang:md5(Binary),
  3. Hash = lists:flatten([io_lib:format("~2.16.0b", [Byte]) || Byte <- binary_to_list(Digest)]).

Haskell

Cabal の MissingH を使った場合
  1. -- import Data.Hash.MD5
  2. contents <- readFile "in.txt"
  3. let hash = md5s $ Str contents

PowerShell

  1. $stream = New-Object System.IO.FileStream in.txt, Open
  2. trap { $stream.Close() }
  3. $provider = [System.Security.Cryptography.MD5CryptoServiceProvider]::Create()
  4. $hash = [string]::Join('', ($provider.ComputeHash($stream) | foreach { $_.ToString('x2') }))
  5. $stream.Close()

F#

  1. // open System.IO
  2. // open System.Security.Cryptography
  3. let bytes = using (new FileStream("in.txt", FileMode.Open))
  4. (MD5CryptoServiceProvider.Create().ComputeHash)
  5. let hash = [for b in bytes -> b.ToString "x2"] |> String.concat ""

C#

  1. // using System.IO;
  2. // using System.Linq;
  3. // using System.Security.Cryptography;
  4. using (var stream = new FileStream("in.txt", FileMode.Open)) {
  5. var bytes = MD5CryptoServiceProvider.Create().ComputeHash(stream);
  6. var hash = string.Join("", bytes.Select(b => b.ToString("x2")));
  7. }

Go

  1. // import "crypto/md5"
  2. // import "io"
  3. // import "os"
  4. var readBytes [1024]byte
  5. file, err := os.Open("in.txt")
  6. if err != nil { return err }
  7. defer file.Close()
  8. summer := md5.New()
  9. for {
  10. n, err := file.Read(readBytes[:])
  11. if err == io.EOF { break }
  12. if err != nil { return err }
  13. summer.Write(readBytes[:n])
  14. }
  15. hashStr := fmt.Sprintf("%0x", summer.Sum([]byte{}))

Rust

md5 を使った場合
  1. // use std::fs;
  2. // use std::io::Read;
  3. // use md5;
  4. let mut file = fs::File::open("in.txt").unwrap();
  5. let mut buf = Vec::new();
  6. file.read_to_end(&mut buf).unwrap();
  7. let digest = md5::compute(buf.as_slice());
  8. let hash = format!("{:x}", digest);

TypeScript

Node.js の場合
  1. // import * as crypto from 'crypto';
  2. // import * as fs from 'fs';
  3. let md = crypto.createHash('md5');
  4. let inStream = fs.ReadStream('in.txt');
  5. inStream.on('data', data => md.update(data));
  6. inStream.on('end', () => {
  7. inStream.destroy();
  8. let hash = md.digest('hex');
  9. ...
  10. });

JavaScript

Node.js の場合
  1. // const crypto = require('crypto');
  2. // const fs = require('fs');
  3. let md = crypto.createHash('md5');
  4. let inStream = fs.ReadStream('in.txt');
  5. inStream.on('data', data => md.update(data));
  6. inStream.on('end', () => {
  7. inStream.destroy();
  8. let hash = md.digest('hex');
  9. ...
  10. });

CoffeeScript

Node.js の場合
  1. # crypto = require 'crypto'
  2. # fs = require 'fs'
  3. md = crypto.createHash 'md5'
  4. inStream = fs.ReadStream 'in.txt'
  5. inStream.on 'data', (data) ->
  6. md.update data
  7. inStream.on 'end', ->
  8. inStream.destroy()
  9. hash = md.digest 'hex'

Ruby

  1. # require 'digest/md5'
  2. hash = open('in.txt', 'rb') {|file| Digest::MD5.hexdigest file.read }

Python

  1. # import hashlib
  2. with open('in.txt', 'rb') as file:
  3. bytes = file.read()
  4. hash = hashlib.md5(bytes).hexdigest()

PHP

  1. if (($contents = file_get_contents('in.txt', FILE_BINARY)) === FALSE) {
  2. $error = error_get_last();
  3. throw new Exception($error['message']);
  4. }
  5. $hash = md5($contents);

Perl

一定のサイズずつ読む
  1. # use Digest::MD5;
  2. open my $in, '<:raw', 'in.txt' or die "Cannot open in.txt; $!";
  3. my $hash = Digest::MD5->new->addfile($in)->hexdigest;
先に全部読む
  1. # use Digest::MD5;
  2. open my $in, '<:raw', 'in.txt' or die "Cannot open in.txt; $!";
  3. my $hash = Digest::MD5::md5_hex <$in>;

XHTMLのファイルを読み込んで解析する

下記のようなファイルを読み込んで、form 要素の action 属性と各 input 要素の name 属性を取得する。
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <html>
  3. <head>
  4. </head>
  5. <body>
  6. <form action="/persons/create" method="post">
  7. Name: <input type="text" name="name" /><br />
  8. Age: <input type="text" name="age" /><br />
  9. <input type="submit" name="submit" value="OK" />
  10. </form>
  11. </body>
  12. </html>

Java

先に全部読む
  1. // import java.io.File;
  2. // import javax.xml.parsers.*;
  3. // import org.w3c.dom.*;
  4. DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  5. Document doc = builder.parse(new File("in.xhtml"));
  6. Node form = doc.getElementsByTagName("form").item(0);
  7. String action = form.getAttributes().getNamedItem("action").getNodeValue();
  8. List<String> names = new ArrayList<String>();
  9. for (int i = 0; true; i++) {
  10. Node elem = form.getChildNodes().item(i);
  11. if (elem == null) break;
  12. if (elem.getNodeName().equals("input")) {
  13. names.add(elem.getAttributes().getNamedItem("name").getNodeValue());
  14. }
  15. }
  1. // import java.io.File;
  2. // import javax.xml.parsers.*;
  3. // import javax.xml.xpath.*;
  4. // import org.w3c.dom.*;
  5. DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  6. Document doc = builder.parse(new File("in.xhtml"));
  7. XPathFactory factory = XPathFactory.newInstance();
  8. String action = (String) factory.newXPath().compile("//form/@action").evaluate(doc, XPathConstants.STRING);
  9. NodeList nodes = (NodeList) factory.newXPath().compile("//input/@name").evaluate(doc, XPathConstants.NODESET);
  10. int length = nodes.getLength();
  11. List<String> names = new ArrayList<String>(length);
  12. for (int i = 0; i < length; i++) {
  13. names.add(nodes.item(i).getNodeValue());
  14. }
順次読み込み
  1. // import java.io.File;
  2. // import javax.xml.parsers.*;
  3. // import org.xml.sax.*;
  4. // import org.xml.sax.helpers.DefaultHandler;
  5. final StringBuilder action = new StringBuilder();
  6. final List<String> names = new ArrayList<String>();
  7. SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
  8. parser.parse(new File("in.xhtml"), new DefaultHandler() {
  9. @Override
  10. public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
  11. if (name.equals("form")) {
  12. action.append(attributes.getValue("action"));
  13. } else if (name.equals("input")) {
  14. names.add(attributes.getValue("name"));
  15. }
  16. }
  17. });
  1. // import java.io.*;
  2. // import javax.swing.text.MutableAttributeSet;
  3. // import javax.swing.text.html.*;
  4. // import javax.swing.text.html.parser.ParserDelegator;
  5. final StringBuilder action = new StringBuilder();
  6. final List<String> names = new ArrayList<String>();
  7. BufferedReader reader = new BufferedReader(new FileReader("in.xhtml"));
  8. try {
  9. new ParserDelegator().parse(reader, new HTMLEditorKit.ParserCallback() {
  10. @Override
  11. public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
  12. if (t.equals(HTML.Tag.INPUT)) {
  13. names.add((String) a.getAttribute(HTML.Attribute.NAME));
  14. }
  15. }
  16. @Override
  17. public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
  18. if (t.equals(HTML.Tag.FORM)) {
  19. action.append(a.getAttribute(HTML.Attribute.ACTION));
  20. }
  21. }
  22. }, false);
  23. } finally {
  24. reader.close();
  25. }

Groovy

先に全部読む
  1. def doc = new XmlParser().parse('in.xhtml')
  2. def form = doc.body.form[0]
  3. def action = form.attribute('action')
  4. def names = form.input*.attribute('name')
  1. def root = new XmlSlurper().parse('in.xhtml')
  2. def action = root.body.form.@action
  3. def names = root.body.form.input*.@name
  1. // import groovy.xml.DOMBuilder
  2. // import groovy.xml.dom.DOMCategory
  3. def doc = new File('in.xhtml').withReader(DOMBuilder.&parse)
  4. def root = doc.documentElement
  5. use (DOMCategory) {
  6. def action = root.'*'.form.'@action'
  7. def names = root.'**'.input*.'@name'
  8. }
順次読み込み
  1. // import java.io.File
  2. // import javax.xml.parsers.*
  3. // import org.xml.sax.Attributes
  4. // import org.xml.sax.helpers.DefaultHandler
  5. def action
  6. def names = []
  7. def parser = SAXParserFactory.newInstance().newSAXParser()
  8. parser.parse(new File('in.xhtml'), new DefaultHandler() {
  9. @Override void startElement(String uri, String localName, String name, Attributes attributes) {
  10. switch (name) {
  11. case 'form':
  12. action = attributes.getValue('action')
  13. break
  14. case 'input':
  15. names << attributes.getValue('name')
  16. break
  17. }
  18. }
  19. })

Scala

先に全部読む
  1. // import scala.xml.XML
  2. val doc = XML.loadFile("in.xhtml") // doc の型は scala.xml.Elem
  3. val action = doc \\ "form" \ "@action" text // action の型は String
  4. val names = doc \\ "input" map(_ \ "@name" text) // names の型は Seq[String]
  1. // import java.io.File
  2. // import scala.xml.parsing.ConstructingParser
  3. val doc = ConstructingParser.fromFile(new File("in.xhtml"), false).document // doc の型は scala.xml.Document
  4. val action = doc \\ "form" \ "@action" text // action の型は String
  5. val names = doc \\ "input" map(_ \ "@name" text) // names の型は Seq[String]
  1. // import scala.xml.Node
  2. // import scala.xml.factory.XMLLoader
  3. val doc = new XMLLoader[Node] {}.loadFile("in.xhtml") // doc の型は scala.xml.Node
  4. val action = doc \\ "form" \ "@action" text // action の型は String
  5. val names = doc \\ "input" map(_ \ "@name" text) // names の型は Seq[String]
  1. // import scala.io.Source
  2. // import scala.xml.parsing.XhtmlParser
  3. val src = Source.fromFile("in.xhtml")
  4. try {
  5. val doc = XhtmlParser(src) // doc の型は scala.xml.NodeSeq
  6. val action = doc \\ "form" \ "@action" text // action の型は String
  7. val names = doc \\ "input" map(_ \ "@name" text) // names の型は Seq[String]
  8. } finally {
  9. src.close
  10. }
順次読み込み
  1. // import scala.collection.mutable.ListBuffer
  2. // import scala.io.Source
  3. // import scala.xml.pull._
  4. var action = ""
  5. val names = new ListBuffer[String]
  6. val src = Source.fromFile("in.xhtml")
  7. try {
  8. new XMLEventReader(src).collect {
  9. case EvElemStart(_, "form", attrs, _) => action = attrs("action").text
  10. case EvElemStart(_, "input", attrs, _) => names += attrs("name").text
  11. }.foreach(_ => ())
  12. } finally {
  13. src.close
  14. }
  1. // import scala.collection.mutable.ListBuffer
  2. // import scala.io.Source
  3. // import scala.xml.pull._
  4. var action = ""
  5. val names = new ListBuffer[String]
  6. val src = Source.fromFile("in.xhtml")
  7. try {
  8. val reader = new XMLEventReader(src)
  9. for (EvElemStart(_, label, attrs, _) <- reader) label match {
  10. case "form" => action = attrs("action").text
  11. case "input" => names += attrs("name").text
  12. case _ => ()
  13. }
  14. } finally {
  15. src.close
  16. }
  1. // import org.xml.sax.Attributes
  2. // import org.xml.sax.helpers.DefaultHandler
  3. // import scala.collection.mutable.ListBuffer
  4. // import scala.xml.XML
  5. // import scala.xml.Source
  6. var action = ""
  7. val names = new ListBuffer[String]
  8. XML.parser.parse(Source.fromFile("in.xhtml"), new DefaultHandler {
  9. override def startElement(uri: String, localName: String, name: String, attributes: Attributes) =
  10. name match {
  11. case "form" => action = attributes.getValue("action")
  12. case "input" => names += attributes.getValue("name")
  13. case _ => ()
  14. }
  15. })

Erlang

先に全部読む
  1. %% -include_lib("xmerl/include/xmerl.hrl").
  2. {Doc, _} = xmerl_scan:file("in.xhtml"),
  3. [ActionAttr|_] = xmerl_xpath:string("//form/@action", Doc),
  4. Action = ActionAttr#xmlAttribute.value,
  5. Names = [Attr#xmlAttribute.value || Attr <- xmerl_xpath:string("//input/@name", Doc)].

Haskell

Cabal の MissingHxml を使った場合
先に全部読む
  1. -- import Data.Maybe.Utils
  2. -- import Text.XML.Light.Input
  3. -- import Text.XML.Light.Proc
  4. -- import Text.XML.Light.Types
  5. contents <- readFile "in.xhtml"
  6. let Just doc = parseXMLDoc contents
  7. let Just formElem = findElement (QName "form" Nothing Nothing) doc
  8. let Just action = findAttr (QName "action" Nothing Nothing) formElem
  9. let names = map forceMaybe $ map (findAttr $ QName "name" Nothing Nothing) $ findElements (QName "input" Nothing Nothing) doc
Cabal の HaXml を使った場合
先に全部読む
  1. -- import Text.XML.HaXml
  2. -- import Text.XML.HaXml.Posn
  3. -- import Text.XML.HaXml.Util
  4. -- import Text.XML.HaXml.Xtract.Parse
  5. contents <- readFile "in.xhtml"
  6. let Document _ _ root _ = xmlParse "" contents
  7. let find xpath root = map contentElem $ xtract id xpath $ CElem root noPos
  8. let getAttr name elem = head $ [value | (name', AttValue [Left value]) <- attrs elem, name' == name]
  9. let [action] = map (getAttr "action") $ find "//form" root
  10. let names = map (getAttr "name") $ find "//input" root
  1. -- import Text.XML.HaXml
  2. -- import Text.XML.HaXml.Posn
  3. -- import Text.XML.HaXml.Util
  4. -- import Text.XML.HaXml.Xtract.Parse
  5. contents <- readFile "in.xhtml"
  6. let Document _ _ root _ = xmlParse "" contents
  7. let find name root = map contentElem $ (deep $ tag name) $ CElem root noPos
  8. let getAttr name elem = head $ [value | (name', AttValue [Left value]) <- attrs elem, name' == name]
  9. let [action] = map (getAttr "action") $ find "form" root
  10. let names = map (getAttr "name") $ find "input" root
順次読み込み
  1. -- import Data.Map
  2. -- import Text.XML.HaXml.SAX
  3. -- import Text.XML.HaXml.Types
  4. contents <- readFile "in.xhtml"
  5. let (elements, Nothing) = saxParse "" contents
  6. let map = foldl f (fromList [("names", [])]) elements where
  7. f map (SaxElementOpen "form" attrs) = foldl fForm map attrs
  8. f map (SaxElementTag "input" attrs) = foldl fInput map attrs
  9. f map _ = map
  10. fForm map ("action", AttValue [Left value]) = insert "action" [value] map
  11. fForm map _ = map
  12. fInput map ("name", AttValue [Left value]) = insert "names" (value : map ! "names") map
  13. fInput map _ = map
  14. let [action] = map ! "action"
  15. let names = reverse $ map ! "names"

PowerShell

先に全部読む
  1. [xml] $doc = cat in.xhtml # System.Xml.XmlDocument
  2. $action = $doc.html.body.form.action
  3. $names = $doc.html.body.form.input | foreach { $_.name }
  1. [xml] $doc = cat in.xhtml # System.Xml.XmlDocument
  2. $action = $doc.SelectSingleNode('//form/@action').Value
  3. $names = $doc.SelectNodes('//input/@name') | foreach { $_.Value }
順次読み込み
  1. $names = @()
  2. $reader = [System.Xml.XmlReader]::Create('in.xhtml')
  3. trap { $reader.Close() }
  4. while ($reader.Read()) {
  5. switch ($reader.NodeType) {
  6. 'Element' {
  7. switch ($reader.Name) {
  8. 'form' { $action = $reader.GetAttribute('action') }
  9. 'input' { $names += $reader.GetAttribute('name') }
  10. }
  11. }
  12. }
  13. }
  14. $reader.Close()

F#

先に全部読む
  1. // open System.Linq
  2. // open System.Xml.Linq
  3. let getAttr name (elem : XElement) = elem.Attribute(XName.Get name).Value
  4. let doc = XDocument.Load "in.xhtml"
  5. let action = doc.Descendants(XName.Get "form") |> Seq.head |> getAttr "action"
  6. let names = doc.Descendants(XName.Get "input") |> Seq.map (getAttr "name")
  1. // open System.Xml
  2. let doc = new XmlDocument()
  3. doc.Load "in.xhtml"
  4. let action = doc.SelectSingleNode("//form/@action").Value
  5. let names = [for node in doc.SelectNodes "//input/@name" -> node.Value]
順次読み込み
  1. // open System.Collections.Generic
  2. // open System.Xml
  3. let mutable action = ""
  4. let names = new List<string>()
  5. use reader = XmlReader.Create "in.xhtml"
  6. while reader.Read() do
  7. match reader.NodeType with
  8. | XmlNodeType.Element ->
  9. match reader.Name with
  10. | "form" -> action <- reader.GetAttribute "action"
  11. | "input" -> names.Add(reader.GetAttribute "name")
  12. | _ -> ()
  13. | _ -> ()

C#

先に全部読む
  1. // using System.Linq;
  2. // using System.Xml.Linq;
  3. var doc = XDocument.Load("in.xhtml");
  4. string action = doc.Descendants("form").First().Attribute("action").Value;
  5. var names = doc.Descendants("input").Select(input => input.Attribute("name").Value);
  1. // using System.Linq;
  2. // using System.Xml.Linq;
  3. var doc = XDocument.Load("in.xhtml");
  4. string action = (from form in doc.Descendants("form")
  5. select form.Attribute("action").Value).First();
  6. var names = from input in doc.Descendants("input") select input.Attribute("name").Value;
  1. // using System.Xml;
  2. XmlDocument doc = new XmlDocument();
  3. doc.Load("in.xhtml");
  4. string action = doc.SelectSingleNode("//form/@action").Value;
  5. List<string> names = new List<string>();
  6. foreach (XmlNode node in doc.SelectNodes("//input/@name")) {
  7. names.Add(node.Value);
  8. }
順次読み込み
  1. // using System.Xml;
  2. string action = null;
  3. List<string> names = new List<string>();
  4. using (XmlReader reader = XmlReader.Create("in.xhtml")) {
  5. while (reader.Read()) {
  6. switch (reader.NodeType) {
  7. case XmlNodeType.Element:
  8. switch (reader.Name) {
  9. case "form":
  10. action = reader.GetAttribute("action");
  11. break;
  12. case "input":
  13. names.Add(reader.GetAttribute("name"));
  14. break;
  15. }
  16. break;
  17. }
  18. }
  19. }

Go

順次読み込み
  1. // import "container/list"
  2. // import "encoding/xml"
  3. // import "io"
  4. // import "os"
  5. type InputTag struct {
  6. Name string `xml:"name,attr"`
  7. }
  8. type FormTag struct {
  9. Action string `xml:"action,attr"`
  10. Input []InputTag `xml:"input"`
  11. }
  1. var action string
  2. names := list.New()
  3. file, err := os.Open("in.xhtml")
  4. if err != nil { return err }
  5. defer file.Close()
  6. parser := xml.NewDecoder(file)
  7. for {
  8. token, err := parser.Token()
  9. if err == io.EOF { break }
  10. if err != nil { return err }
  11. startElem, ok := token.(xml.StartElement)
  12. if ok && startElem.Name.Local == "form" {
  13. var form FormTag
  14. err = parser.DecodeElement(&form, &startElem)
  15. if err != nil { return err }
  16. action = form.Action
  17. for _, input := range form.Input {
  18. names.PushBack(input.Name)
  19. }
  20. break
  21. }
  22. }

Ruby

先に全部読む
  1. # require 'rexml/document'
  2. doc = REXML::Document.new File.new('in.xhtml')
  3. action = doc.elements['//form/@action'].value
  4. names = doc.elements.collect('//input') {|input| input.attributes['name'] }
  1. # require 'rexml/document'
  2. doc = REXML::Document.new File.new('in.xhtml')
  3. form = doc.elements['//form']
  4. action = form.attributes['action']
  5. names = form.elements.collect('input') {|input| input.attributes['name'] }
先に全部読む
Nokogiri を使った場合
  1. # require 'nokogiri'
  2. doc = open('in.xhtml') {|file| Nokogiri file }
  3. action = doc.at(:form)[:action]
  4. names = (doc / :input).collect {|input| input[:name] }
  1. # require 'nokogiri'
  2. doc = open('in.xhtml') {|file| Nokogiri file }
  3. action = doc.search(:form).first.attr :action
  4. names = doc.search(:input).collect {|input| input.attr :name }
  1. # require 'nokogiri'
  2. doc = open('in.xhtml') {|file| Nokogiri file }
  3. action = doc.xpath('//form/@action').first.text
  4. names = doc.xpath('//input/@name').collect(&:text)
順次読み込み
  1. # require 'rexml/document'
  2. # require 'rexml/streamlistener'
  3. class << listener = {:names => []}
  4. include REXML::StreamListener
  5. def tag_start(name, attrs)
  6. case name
  7. when 'form'
  8. self[:action] = attrs['action']
  9. when 'input'
  10. self[:names] << attrs['name']
  11. end
  12. end
  13. end
  14. REXML::Parsers::StreamParser.new(File.read('in.xhtml'), listener).parse
  15. action = listener[:action]
  16. names = listener[:names]
順次読み込み
Nokogiri を使った場合
  1. # require 'nokogiri'
  2. action = nil
  3. names = []
  4. open 'in.xhtml' do |file|
  5. Nokogiri::XML::Reader(file).each do |node|
  6. case node.name
  7. when 'form'
  8. action = node.attribute 'action'
  9. when 'input'
  10. names << node.attribute('name')
  11. end
  12. end
  13. end
  1. # require 'nokogiri'
  2. class Document < Nokogiri::XML::SAX::Document
  3. attr_reader :action, :names
  4. def initialize
  5. @names = []
  6. end
  7. def start_element name, attrs
  8. attr_hash = Hash[*attrs.flatten]
  9. case name
  10. when 'form'
  11. @action = attr_hash['action']
  12. when 'input'
  13. @names << attr_hash['name']
  14. end
  15. end
  16. end
  17. xml = open('in.xhtml') {|file| file.read }
  18. doc = Document.new
  19. Nokogiri::XML::SAX::Parser.new(doc).parse(xml)
  20. action = doc.action
  21. names = doc.names

Python

先に全部読む
  1. # import xml.etree.ElementTree
  2. tree = xml.etree.ElementTree.ElementTree()
  3. tree.parse('in.xhtml')
  4. form = tree.find('body/form')
  5. action = form.attrib['action']
  6. names = [input.attrib['name'] for input in form.findall('input')]
順次読み込み
  1. # import xml.sax
  2. # import xml.sax.handler
  3. class Handler(xml.sax.handler.ContentHandler):
  4. action = ''
  5. names = []
  6. def startElement(self, name, attrs):
  7. if name == 'form':
  8. self.action = attrs['action']
  9. elif name == 'input':
  10. self.names.append(attrs['name'])
  1. handler = Handler()
  2. xml.sax.parse('in.xhtml', handler)
  3. action = handler.action
  4. names = handler.names
順次読み込み
Python 3.0以降
  1. # import html.parser
  2. class Parser(html.parser.HTMLParser):
  3. action = ''
  4. names = []
  5. def handle_starttag(self, tag, attrs):
  6. if tag == 'form':
  7. self.action = dict(attrs)['action']
  8. def handle_startendtag(self, tag, attrs):
  9. if tag == 'input':
  10. self.names.append(dict(attrs)['name'])
  1. parser = Parser()
  2. with open('in.xhtml', 'r') as file:
  3. parser.feed(file.read())
  4. action = parser.action
  5. names = parser.names

PHP

  1. $doc = new DOMDocument();
  2. if (! $doc->load('in.xhtml')) {
  3. throw new Exception('Cannot load in.xhtml');
  4. }
  5. $xpath = new DOMXPath($doc);
  6. $action = $xpath->evaluate('string(//form/@action)');
  7. $names = [];
  8. foreach ($xpath->query('//input') as $input) {
  9. array_push($names, $input->getAttribute('name'));
  10. }
  1. if (($xml = simplexml_load_file('in.xhtml')) === FALSE) {
  2. throw new Exception('Cannot load in.xhtml');
  3. }
  4. $form = $xml->xpath('//form');
  5. $action = (string)$form[0]['action'];
  6. $names = [];
  7. foreach ($xml->xpath('//input') as $input) {
  8. array_push($names, (string)$input['name']);
  9. }

Perl

CPAN の XML::LibXML を使った場合
  1. # use XML::LibXML;
  2. my $doc = XML::LibXML->load_xml(location => 'in.xhtml');
  3. my $action = $doc->findvalue('//form/@action');
  4. my @names = map $_->value, $doc->findnodes('//input/@name');
CPAN の XML::Simple を使った場合
  1. # use XML::Simple;
  2. my $hash = XML::Simple->new->XMLin('in.xhtml');
  3. my $action = $hash->{body}{form}{action};
  4. my @names = keys %{$hash->{body}{form}{input}};
CPAN の XML::TreePP を使った場合
  1. # use XML::TreePP;
  2. my $hash = XML::TreePP->new->parsefile('in.xhtml');
  3. my $action = $hash->{html}{body}{form}{-action}; # ハイフン付きの語は属性名を表す
  4. my @names = map $_->{-name}, @{$hash->{html}{body}{form}{input}};

JSONデータを解析する

人物リストのJSONデータから、20歳の人全員の名前を取得する。

Java

org.json パッケージを使った場合
  1. String jsonStr = "{'members': ["
  2. + "{'name': 'Taro', 'age': 20}, "
  3. + "{'name': 'Jiro', 'age': 17}, "
  4. + "{'name': 'Saburo', 'age': 15}, "
  5. + "{'name': 'Hanako', 'age': 20}"
  6. + "]}";
  1. // import org.json.*;
  2. List<String> result = new ArrayList<String>();
  3. JSONArray members = new JSONObject(jsonStr).getJSONArray("members");
  4. int length = members.length();
  5. for (int i = 0; i < length; i++) {
  6. JSONObject member = members.getJSONObject(i);
  7. if (member.getInt("age") == 20) {
  8. result.add(member.getString("name"));
  9. }
  10. }

Groovy

  1. def jsonStr = """
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }"""
  1. // import groovy.json.JsonSlurper
  2. def all = new JsonSlurper().parseText(jsonStr)
  3. def result = all.members.findAll { it.age == 20 } *.name
org.json パッケージを使った場合
  1. // import org.json.JSONObject
  2. def members = new JSONObject(jsonStr).members
  3. def memberList = (0 ..< members.length()).collect(members.&get)
  4. def result = memberList.findAll { it.age == 20 } *.name

Scala

  1. val json = """
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }
  10. """;
  1. // import scala.util.parsing.json.JSON
  2. val result = (JSON.parseFull(json): @unchecked) match {
  3. case Some(all: Map[String, List[Map[Any, Any]]]) =>
  4. for (member <- all("members"); if member("age") == 20) yield member("name")
  5. }

Haskell

Cabal の json を使った場合
  1. let json = concat ["{",
  2. " \"members\": [",
  3. " {\"name\": \"Taro\", \"age\": 20},",
  4. " {\"name\": \"Jiro\", \"age\": 17},",
  5. " {\"name\": \"Saburo\", \"age\": 15},",
  6. " {\"name\": \"Hanako\", \"age\": 20}",
  7. " ]",
  8. "}"]
  1. -- import Text.JSON.ReadP
  2. -- import Text.JSON.Types
  3. -- import Text.ParserCombinators.ReadP
  4. let [(JSObject obj, "")] = readP_to_S p_value json
  5. let Just (JSArray members) = get_field obj "members" :: Maybe JSValue
  6. let result = [ name
  7. | JSObject member <- members
  8. , let Just (JSString (JSONString name)) = get_field member "name"
  9. , let Just (JSRational _ age) = get_field member "age"
  10. , age == 20]

PowerShell

Json.NET を使った場合
  1. $json = @'
  2. {
  3. 'members': [
  4. {'name': 'Taro', 'age': 20},
  5. {'name': 'Jiro', 'age': 17},
  6. {'name': 'Saburo', 'age': 15},
  7. {'name': 'Hanako', 'age': 20}
  8. ]
  9. }
  10. '@
  1. # [void] [System.Reflection.Assembly]::LoadFrom('Newtonsoft.Json.dll')
  2. $jobj = [Newtonsoft.Json.Linq.JObject]::Parse($json)
  3. $result = $jobj['members'] | where { [int] $_['age'] -eq 20 } | foreach { $_['name'].Value }

F#

  1. let json = @"
  2. {
  3. ""members"": [
  4. {""name"": ""Taro"", ""age"": 20},
  5. {""name"": ""Jiro"", ""age"": 17},
  6. {""name"": ""Saburo"", ""age"": 15},
  7. {""name"": ""Hanako"", ""age"": 20}
  8. ]
  9. }"
  1. // open System.IO
  2. // open System.Runtime.Serialization
  3. // open System.Runtime.Serialization.Json
  4. // open System.Text
  5. type All =
  6. val mutable members : Member[]
  7. and Member =
  8. val mutable name : string
  9. val mutable age : int
  10. let stream = new MemoryStream(Encoding.UTF8.GetBytes json)
  11. let all = (DataContractJsonSerializer typeof<All>).ReadObject stream :?> All
  12. let result = [
  13. for _member in all.members do
  14. if _member.age = 20 then yield _member.name
  15. ]
Json.NET を使った場合
  1. // open Newtonsoft.Json.Linq
  2. let jobj = JObject.Parse json
  3. let result = [
  4. for _member in jobj.["members"] do
  5. if int _member.["age"] = 20 then yield string <| _member.Value "name"
  6. ]

C#

  1. var json = @"
  2. {
  3. ""members"": [
  4. {""name"": ""Taro"", ""age"": 20},
  5. {""name"": ""Jiro"", ""age"": 17},
  6. {""name"": ""Saburo"", ""age"": 15},
  7. {""name"": ""Hanako"", ""age"": 20}
  8. ]
  9. }";
  1. // using System.IO;
  2. // using System.Linq;
  3. // using System.Runtime.Serialization;
  4. // using System.Runtime.Serialization.Json;
  5. [DataContract]
  6. public class All {
  7. [DataMember]
  8. public Member[] members { get; private set; }
  9. [DataContract]
  10. public class Member {
  11. [DataMember]
  12. public string name { get; private set; }
  13. [DataMember]
  14. public int age { get; private set; }
  15. }
  16. }
  1. var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
  2. var all = (All)new DataContractJsonSerializer(typeof(All)).ReadObject(stream);
  3. var result = from member in all.members
  4. where member.age == 20
  5. select member.name;
Json.NET を使った場合
  1. // using System.Linq;
  2. // using Newtonsoft.Json.Linq;
  3. var jobj = JObject.Parse(json);
  4. var result = from member in jobj["members"]
  5. where (int)member["age"] == 20
  6. select (string)member["name"];

Go

  1. jsonStr := `
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }`
  1. // import "container/list"
  2. // import "encoding/json"
  3. // import "strings"
  4. type All struct {
  5. Members []Member `json:"members"`
  6. }
  7. type Member struct {
  8. Name string `json:"name"`
  9. Age int `json:"age"`
  10. }
  1. var all All
  2. result := list.New()
  3. decoder := json.NewDecoder(strings.NewReader(jsonStr))
  4. err := decoder.Decode(&all)
  5. if err != nil { return err }
  6. for _, member := range all.Members {
  7. if member.Age == 20 {
  8. result.PushBack(member.Name)
  9. }
  10. }

Rust

serde・serde_json を使った場合
  1. // use serde;
  2. #[derive(serde::Serialize, serde::Deserialize)]
  3. struct Person<'a> {
  4. name: &'a str,
  5. age: i32,
  6. }
  1. // use std::collections::HashMap;
  2. // use serde_json;
  3. let json = r#"
  4. {
  5. "members": [
  6. {"name": "Taro", "age": 20},
  7. {"name": "Jiro", "age": 17},
  8. {"name": "Saburo", "age": 15},
  9. {"name": "Hanako", "age": 20}
  10. ]
  11. }
  12. "#;
  13. let map: HashMap<&str, Vec<Person>> = serde_json::from_str(json).unwrap();
  14. let result: Vec<_> = map["members"].iter().filter(|p| p.age == 20).map(|p| p.name).collect();

TypeScript

  1. let json = `
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15}
  7. ]
  8. }
  9. `;
  1. let all = JSON.parse(json);
  2. let result = all.members
  3. .filter(member => member.age === 20)
  4. .map(member => member.name);

JavaScript

  1. let json = `
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15}
  7. ]
  8. }
  9. `;
  1. let all = JSON.parse(json);
  2. let result = all.members
  3. .filter(member => member.age === 20)
  4. .map(member => member.name);

CoffeeScript

  1. json = '''
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15}
  7. ]
  8. }
  9. '''
  1. all = JSON.parse json
  2. result = all.members
  3. .filter (member) -> member.age == 20
  4. .map (member) -> member.name

Ruby

Ruby on Rails を使った場合
  1. json = <<'END'
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }
  10. END
  1. all = ActiveSupport::JSON::decode json
  2. result = all['members'].select {|m| m['age'] == 20 }.collect {|m| m['name'] }

Python

  1. json_str = '''
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }
  10. '''
  1. # import json
  2. all = json.loads(json_str)
  3. result = [m['name'] for m in all['members'] if m['age'] == 20]

PHP

  1. $json = <<<'END'
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }
  10. END;
  1. if (($all = json_decode($json)) === NULL) {
  2. throw new Exception('Cannot decode');
  3. }
  4. $result = array_filter($all->members, function($member) { return $member->age === 20; });
  5. $result = array_map(function($member) { return $member->name; }, $result);

Perl

CPAN の JSON を使った場合
  1. my $json = <<'END';
  2. {
  3. "members": [
  4. {"name": "Taro", "age": 20},
  5. {"name": "Jiro", "age": 17},
  6. {"name": "Saburo", "age": 15},
  7. {"name": "Hanako", "age": 20}
  8. ]
  9. }
  10. END
  1. # use JSON;
  2. my $all = decode_json($json);
  3. my @result = map $_->{name}, grep $_->{age} == 20, @{$all->{members}};

HTTP でテキストデータを GET する

Java

  1. // import java.net.URI;
  2. // import java.net.http.*;
  3. HttpClient client = HttpClient.newHttpClient();
  4. HttpRequest request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/")).GET().build();
  5. String result = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
Apache HttpClient 5.xを使った場合
  1. // import org.apache.hc.client5.http.fluent.Request;
  2. String result = Request.get("http://www.***.ne.jp/").execute().returnContent().asString();
Commons IO を使った場合
  1. // import java.net.URL;
  2. // import org.apache.commons.io.IOUtils;
  3. String result = IOUtils.toString(new URL("http://www.***.ne.jp/"), "UTF-8");

Groovy

  1. // import java.net.URL
  2. def result = new URL('http://www.***.ne.jp/').getText('UTF-8')

Kotlin

  1. // import java.net.URI
  2. // import java.net.http.*
  3. val client = HttpClient.newHttpClient()
  4. val request = HttpRequest.newBuilder(URI("http://www.***.ne.jp/")).GET().build()
  5. val result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
  1. // import org.apache.hc.client5.http.fluent.Request
  2. val result = Request.get("http://www.***.ne.jp/").execute().returnContent().asString()
Commons IO を使った場合
  1. // import java.net.URL
  2. // import org.apache.commons.io.IOUtils
  3. val result = IOUtils.toString(URL("http://www.***.ne.jp/"), "UTF-8")

Scala

  1. // import java.net.URL
  2. // import scala.sys.process._
  3. val result = new URL("http://www.***.ne.jp/").cat !!
  1. // import scala.io.Source
  2. val src = Source.fromURL("http://www.***.ne.jp/", "UTF-8")
  3. val result = try { src.mkString } finally { src.close }
Dispatch を使った場合
  1. // import dispatch._
  2. val http = new Http
  3. val result = http(url("http://www.***.ne.jp/") >\ "UTF-8" as_str)
scalaj-http を使った場合
  1. // import scalaj.http.Http
  2. val result = Http("http://www.***.ne.jp/").asString
scala-io を使った場合
  1. // import java.net.URL
  2. // import scalax.io.Codec
  3. // import scalax.io.JavaConverters._
  4. val result = new URL("http://www.***.ne.jp").asInput.slurpString(Codec.UTF8)
  1. // import scalax.io.Codec
  2. // import scalax.io.Resource
  3. val result = Resource.fromURL("http://www.***.ne.jp").slurpString(Codec.UTF8)

Erlang

  1. inets:start(),
  2. {ok, {{_, 200, _}, _, Result}} = httpc:request("http://www.***.ne.jp/").

Haskell

Cabal の HTTP を使った場合
  1. -- import Network.HTTP
  2. Right (Response (2, 0, 0) _ _ result) <- simpleHTTP $ getRequest "http://www.***.ne.jp/"

PowerShell

  1. $bytes = (New-Object System.Net.WebClient).DownloadData('http://www.***.ne.jp')
  2. $result = [System.Text.Encoding]::UTF8.GetString($bytes)

F#

  1. // open System.Net
  2. // open System.Text
  3. let result = (new WebClient()).DownloadData "http://www.***.ne.jp/" |> Encoding.UTF8.GetString

C#

  1. // using System.Net;
  2. byte[] bytes = new WebClient().DownloadData("http://www.***.ne.jp/");
  3. string result = Encoding.UTF8.GetString(bytes);

Go

  1. // import "bytes"
  2. // import "io"
  3. // import "net/http"
  4. response, err := http.Get("http://www.***.ne.jp/")
  5. if err != nil { return err }
  6. defer response.Body.Close()
  7. if response.StatusCode == http.StatusOK {
  8. var buf bytes.Buffer
  9. var bytes [1024]byte
  10. for {
  11. n, err := response.Body.Read(bytes[:])
  12. if err == io.EOF { break }
  13. if err != nil { return err }
  14. buf.Write(bytes[:n])
  15. }
  16. result := buf.String()
  17. }

Rust

reqwest を使った場合
  1. // use reqwest;
  2. let response = reqwest::get("http://www.***.ne.jp/").await.unwrap();
  3. let result = response.text().await.unwrap();

Ruby

  1. # require 'open-uri'
  2. result = URI.open('http://www.***.ne.jp/') {|io| io.read }
  1. # require 'net/http'
  2. result = Net::HTTP.get_response(URI.parse('http://www.***.ne.jp/')).body
  1. # require 'net/http'
  2. result = Net::HTTP.start('www.***.ne.jp', 80) {|http| http.get('/').body }

Python

  1. # import urllib.request
  2. with urllib.request.urlopen('http://www.***.ne.jp/') as response:
  3. result = response.read().decode('UTF-8')
  1. # import http.client
  2. conn = http.client.HTTPConnection('www.***.ne.jp')
  3. conn.request('GET', '/')
  4. try:
  5. response = conn.getresponse()
  6. if response.status == http.client.OK:
  7. result = response.read().decode('UTF-8')
  8. finally:
  9. conn.close()

PHP

  1. if (($result = file_get_contents('http://www.***.ne.jp/')) === FALSE) {
  2. $error = error_get_last();
  3. throw new Exception($error['message']);
  4. }
  1. $ch = curl_init('http://www.***.ne.jp/');
  2. curl_setopt_array($ch, [
  3. CURLOPT_FAILONERROR => TRUE,
  4. CURLOPT_RETURNTRANSFER => TRUE
  5. ]);
  6. $result = curl_exec($ch);
  7. $error = $result === FALSE ? curl_error($ch) : NULL;
  8. curl_close($ch);
  9. if ($error) {
  10. throw new Exception($error);
  11. }

Perl

  1. # use LWP::UserAgent;
  2. my $response = LWP::UserAgent->new->get('http://www.***.ne.jp/');
  3. die $response->request->uri . ': ' . $response->status_line unless $response->is_success;
  4. my $result = $response->content;

HTTP でフォームデータを POST する

Java

  1. // import java.net.*;
  2. // import java.net.http.*;
  3. HttpClient client = HttpClient.newHttpClient();
  4. String data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password";
  5. HttpRequest request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
  6. .POST(HttpRequest.BodyPublishers.ofString(data))
  7. .build();
  8. String result = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
Apache HttpClient 5.xを使った場合
  1. // import java.nio.charset.StandardCharsets;
  2. // import org.apache.hc.client5.http.fluent.*;
  3. String result = Request.post("http://www.***.ne.jp/")
  4. .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
  5. .execute().returnContent().asString();

Groovy

  1. // import java.net.*
  2. // import java.net.http.*
  3. def client = HttpClient.newHttpClient()
  4. def data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
  5. def request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
  6. .POST(HttpRequest.BodyPublishers.ofString(data))
  7. .build()
  8. def result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
  1. // import java.nio.charset.StandardCharsets
  2. // import org.apache.hc.client5.http.fluent.*
  3. def result = Request.post("http://www.***.ne.jp/")
  4. .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
  5. .execute().returnContent().asString()

Kotlin

  1. // import java.net.*
  2. // import java.net.http.*
  3. val client = HttpClient.newHttpClient()
  4. val data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
  5. val request = HttpRequest.newBuilder(URI("http://www.***.ne.jp/"))
  6. .POST(HttpRequest.BodyPublishers.ofString(data))
  7. .build()
  8. val result = client.send(request, HttpResponse.BodyHandlers.ofString()).body()
Apache HttpClient 5.xを使った場合
  1. // import java.nio.charset.StandardCharsets
  2. // import org.apache.hc.client5.http.fluent.*
  3. val result = Request.post("http://www.***.ne.jp/")
  4. .bodyForm(Form.form().add("NAME", "名前").add("PASSWORD", "password").build(), StandardCharsets.UTF_8)
  5. .execute().returnContent().asString()

Scala

  1. // import java.net._
  2. // import java.net.http._
  3. val client = HttpClient.newHttpClient
  4. val data = "NAME=" + URLEncoder.encode("名前", "UTF-8") + "&PASSWORD=password"
  5. val request = HttpRequest.newBuilder(new URI("http://www.***.ne.jp/"))
  6. .POST(HttpRequest.BodyPublishers ofString data)
  7. .build
  8. val result = client.send(request, HttpResponse.BodyHandlers.ofString).body
Apache HttpClient 5.xを使った場合
  1. // import java.nio.charset.StandardCharsets
  2. // import org.apache.hc.client5.http.fluent._
  3. val result = Request.post("http://www.***.ne.jp/")
  4. .bodyForm(Form.form.add("NAME", "名前").add("PASSWORD", "password").build, StandardCharsets.UTF_8)
  5. .execute.returnContent.asString
Dispatch を使った場合
  1. // import dispatch._
  2. val http = new Http
  3. val params = List("NAME" -> "名前", "PASSWORD" -> "password")
  4. val result = http(url("http://www.***.ne.jp/") << params >\ "UTF-8" as_str)
scalaj-http を使った場合
  1. // import scalaj.http.Http
  2. val params = List("NAME" -> "名前", "PASSWORD" -> "password")
  3. val result = Http.post("http://www.***.ne.jp/").params(params).asString

Erlang

  1. inets:start(),
  2. Request = {
  3. "http://www.***.ne.jp",
  4. [],
  5. "application/x-www-form-urlencoded",
  6. "NAME=" ++ edoc_lib:escape_uri("名前") ++ "&PASSWORD=password"
  7. },
  8. {ok, {{_, 200, _}, _, Result}} = httpc:request(post, Request, [], []).

Haskell

Cabal の HTTP を使った場合
  1. -- import Network.HTTP
  2. -- import Network.URI
  3. let Just uri = parseURI("http://www.***.ne.jp/")
  4. let body = urlEncodeVars [("NAME", "名前"), ("PASSWORD", "password")]
  5. let headers = [Header HdrContentType "application/x-www-form-urlencoded",
  6. Header HdrContentLength $ show $ length body
  7. ]
  8. let request = Request uri POST headers body
  9. Right (Response (2, 0, 0) _ _ result) <- simpleHTTP request

PowerShell

  1. $request = [System.Net.WebRequest]::Create('http://www.***.ne.jp/')
  2. $request.Method = 'POST'
  3. $request.ContentType = 'application/x-www-form-urlencoded'
  4. $paramDict = @{NAME = '名前'; PASSWORD = 'password'}
  5. $body = [string]::Join('&', ($paramDict.Keys | foreach { $_ + '=' + [System.Web.HttpUtility]::UrlEncode($paramDict[$_], [System.Text.Encoding]::UTF8) }))
  6. $writer = New-Object System.IO.StreamWriter($request.GetRequestStream(), [System.Text.Encoding]::ASCII)
  7. &{
  8. $writer.Write($body)
  9. $writer.Close()
  10. trap { $writer.Close(); break }
  11. }
  12. $response = $request.GetResponse()
  13. &{
  14. $reader = New-Object System.IO.StreamReader($response.GetResponseStream(), [System.Text.Encoding]::UTF8)
  15. &{
  16. $result = $reader.ReadToEnd()
  17. $reader.Close()
  18. trap { $reader.Close(); break }
  19. }
  20. $response.Close()
  21. trap { $response.Close(); break }
  22. }

F#

  1. // open System
  2. // open Systm.IO
  3. // open System.Net
  4. // open System.Text
  5. // open System.Web
  6. let request = WebRequest.Create "http://www.***.ne.jp/"
  7. request.Method <- "POST"
  8. request.ContentType <- "application/x-www-form-urlencoded"
  9. let paramMap = Map.ofList [("NAME", "名前"); ("PASSWORD", "password")]
  10. let body = String.Join("&",
  11. paramMap |> Seq.map (fun pair -> pair.Key + "=" + HttpUtility.UrlEncode(pair.Value, Encoding.UTF8)))
  12. let writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)
  13. try
  14. writer.Write body
  15. finally
  16. writer.Close()
  17. use response = request.GetResponse()
  18. use reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)
  19. let result = reader.ReadToEnd()

C#

  1. // using System.Collections.Generic;
  2. // using System.IO;
  3. // using System.Linq;
  4. // using System.Net;
  5. // using System.Web;
  6. var request = WebRequest.Create("http://www.***.ne.jp/");
  7. request.Method = "POST";
  8. request.ContentType = "application/x-www-form-urlencoded";
  9. var paramDict = new Dictionary<string, string> {{"NAME", "名前"}, {"PASSWORD", "password"}};
  10. var body = string.Join("&",
  11. from pair in paramDict
  12. select pair.Key + "=" + HttpUtility.UrlEncode(pair.Value, Encoding.UTF8));
  13. using (var writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)) {
  14. writer.Write(body);
  15. }
  16. using (var response = request.GetResponse()) {
  17. using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) {
  18. string result = reader.ReadToEnd();
  19. }
  20. }

Go

  1. // import "bytes"
  2. // import "io"
  3. // import "net/http"
  4. params := map[string][]string{
  5. "NAME":[]string{"名前"},
  6. "PASSWORD":[]string{"password"}
  7. }
  8. response, err := http.PostForm("http://www.***.ne.jp/", params)
  9. if err != nil { return err }
  10. defer response.Body.Close()
  11. if response.StatusCode == http.StatusOK {
  12. var buf bytes.Buffer
  13. var bytes [1024]byte
  14. for {
  15. n, err := response.Body.Read(bytes[:])
  16. if err == io.EOF { break }
  17. if err != nil { return err }
  18. buf.Write(bytes[:n])
  19. }
  20. result := buf.String()
  21. }

Rust

reqwest を使った場合
  1. // use reqwest;
  2. let client = reqwest::Client::new();
  3. let params = [("NAME", "名前"), ("PASSWORD", "password")];
  4. let response = client.post("http://www.***.ne.jp/").form(&params).send().await.unwrap();
  5. let result = response.text().await.unwrap();

Ruby

  1. # require 'net/http'
  2. response = Net::HTTP.post_form URI.parse('http://www.***.ne.jp/'), :NAME => '名前', :PASSWORD => 'password'
  3. result = response.body

Python

  1. # import urllib.parse
  2. # import urllib.request
  3. body = urllib.parse.urlencode({'NAME': '名前', 'PASSWORD': 'password'})
  4. response = urllib.request.urlopen('http://www.***.ne.jp/', body)
  5. try:
  6. result = response.read().decode('UTF-8')
  7. finally:
  8. response.close()
  1. # import http.client
  2. # import urllib.parse
  3. body = urllib.parse.urlencode({'NAME': '名前', 'PASSWORD': 'password'})
  4. conn = http.client.HTTPConnection('www.***.ne.jp')
  5. conn.request('POST', '/', body, {'Content-Type': 'application/x-www-form-urlencoded'})
  6. try:
  7. response = conn.getresponse()
  8. if response.status == http.client.OK:
  9. result = response.read().decode('UTF-8')
  10. finally:
  11. conn.close()

PHP

  1. $ch = curl_init('http://www.***.ne.jp/');
  2. curl_setopt_array($ch, [
  3. CURLOPT_FAILONERROR => TRUE,
  4. CURLOPT_POST => TRUE,
  5. CURLOPT_POSTFIELDS => ['NAME' => '名前', 'PASSWORD' => 'password'],
  6. CURLOPT_RETURNTRANSFER => TRUE
  7. ]);
  8. $result = curl_exec($ch);
  9. $error = $result === FALSE ? curl_error($ch) : NULL;
  10. curl_close($ch);
  11. if ($error) {
  12. throw new Exception($error);
  13. }

Perl

  1. # use LWP::UserAgent;
  2. my $response = LWP::UserAgent->new->post('http://www.***.ne.jp/', {NAME => '名前', PASSWORD => 'password'});
  3. die $response->request->uri . ': ' . $response->status_line unless $response->is_success;
  4. my $result = $response->content;

HTTPS でファイルをダウンロードする

サーバ証明書にルートCAの署名がされていなかったり、発行先名がアクセス先と異なっていても良しとする場合。

Java

  1. // import java.io.*;
  2. // import java.net.*;
  3. // import java.security.*;
  4. // import java.security.cert.*;
  5. // import javax.net.ssl.*;
  6. // サーバ証明書の発行先を確認しない HostnameVerifier
  7. public class IrresponsibleHostnameVerifier implements HostnameVerifier {
  8. @Override
  9. public boolean verify(String hostname, SSLSession session) { return true; }
  10. }
  11. // サーバ証明書の署名を確認しない X509TrustManager
  12. public class IrresponsibleX509TrustManager implements X509TrustManager {
  13. @Override
  14. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  15. @Override
  16. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  17. @Override
  18. public X509Certificate[] getAcceptedIssuers() { return null; }
  19. }
  1. Authenticator.setDefault(new Authenticator() {
  2. @Override
  3. protected PasswordAuthentication getPasswordAuthentication() {
  4. switch (getRequestorType()) {
  5. case PROXY:
  6. return new PasswordAuthentication("proxyUserName", "proxyPassword".toCharArray());
  7. case SERVER:
  8. return new PasswordAuthentication("wwwUserName", "wwwPassword".toCharArray());
  9. }
  10. return null;
  11. }
  12. });
  13. URL url = new URL("https://www.***.ne.jp/");
  14. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.***.ne.jp", 80));
  15. HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy); // HttpsURLConnection は try-with-resources 構文に対応していない
  16. try {
  17. connection.setConnectTimeout(5000); // 5秒でタイムアウトにする
  18. connection.setReadTimeout(5000); // 5秒でタイムアウトにする
  19. connection.setRequestProperty("User-Agent", "Mozilla/4.0");
  20. SSLContext context = SSLContext.getInstance("SSL");
  21. context.init(null, new TrustManager[] {new IrresponsibleX509TrustManager()}, null);
  22. connection.setSSLSocketFactory(context.getSocketFactory()); // サーバ証明書の署名を確認しない
  23. connection.setHostnameVerifier(new IrresponsibleHostnameVerifier()); // サーバ証明書の発行先を確認しない
  24. try (InputStream in = connection.getInputStream()) {
  25. try (FileOutputStream out = new FileOutputStream("index.html")) {
  26. in.transferTo(out);
  27. }
  28. }
  29. } finally {
  30. connection.disconnect();
  31. }
Apache HttpClient 4.xを使った場合
  1. // import java.io.*;
  2. // import java.security.cert.*;
  3. // import javax.net.ssl.*;
  4. // import org.apache.http.*;
  5. // import org.apache.http.auth.*;
  6. // import org.apache.http.client.*;
  7. // import org.apache.http.client.methods.HttpGet;
  8. // import org.apache.http.conn.params.ConnRoutePNames;
  9. // import org.apache.http.conn.scheme.Scheme;
  10. // import org.apache.http.conn.ssl.SSLSocketFactory;
  11. // import org.apache.http.impl.client.*;
  12. // import org.apache.http.params.*;
  13. // サーバ証明書の署名を確認しない X509TrustManager
  14. public class IrresponsibleX509TrustManager implements X509TrustManager {
  15. @Override
  16. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  17. @Override
  18. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  19. @Override
  20. public X509Certificate[] getAcceptedIssuers() { return null; }
  21. }
  1. DefaultHttpClient client = new DefaultHttpClient();
  2. HttpParams params = client.getParams();
  3. params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80));
  4. params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 5秒でタイムアウトにする
  5. params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // 5秒でタイムアウトにする
  6. BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
  7. credsProvider.setCredentials(new AuthScope("proxy.***.ne.jp", 80),
  8. new UsernamePasswordCredentials("proxyUserName", "proxyPassword"));
  9. credsProvider.setCredentials(new AuthScope("www.***.ne.jp", 443),
  10. new UsernamePasswordCredentials("wwwUserName", "wwwPassword"));
  11. client.setCredentialsProvider(credsProvider);
  12. SSLContext context = SSLContext.getInstance("SSL");
  13. context.init(null, new TrustManager[] {new IrresponsibleX509TrustManager()}, null); // サーバ証明書の署名を確認しない
  14. SSLSocketFactory socketFactory
  15. = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // サーバ証明書の発行先を確認しない
  16. client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
  17. HttpGet get = new HttpGet("https://www.***.ne.jp/");
  18. get.setHeader("User-Agent", "Mozilla/4.0");
  19. client.execute(get, new ResponseHandler<Void>() {
  20. @Override
  21. public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  22. StatusLine statusLine = response.getStatusLine();
  23. switch (statusLine.getStatusCode()) {
  24. case HttpStatus.SC_OK:
  25. try (FileOutputStream out = new FileOutputStream("index.html")) {
  26. response.getEntity().writeTo(out);
  27. }
  28. return null;
  29. default:
  30. throw new IOException(statusLine.toString());
  31. }
  32. }
  33. });

Groovy

  1. // import java.net.*
  2. // import java.security.*
  3. // import java.security.cert.*
  4. // import javax.net.ssl.*
  5. Authenticator.default = new Authenticator() {
  6. @Override PasswordAuthentication getPasswordAuthentication() {
  7. switch (requestorType) {
  8. case Authenticator.RequestorType.PROXY:
  9. return new PasswordAuthentication('proxyUserName', 'proxyPassword')
  10. case Authenticator.RequestorType.SERVER:
  11. return new PasswordAuthentication('wwwUserName', 'wwwPassword')
  12. }
  13. null
  14. }
  15. }
  16. def url = new URL('https://www.***.ne.jp/')
  17. def proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress('proxy.***.ne.jp', 80))
  18. def connection = url.openConnection(proxy)
  19. try {
  20. connection.connectTimeout = 5000 // 5秒でタイムアウトにする
  21. connection.readTimeout = 5000 // 5秒でタイムアウトにする
  22. connection.setRequestProperty 'User-Agent', 'Mozilla/4.0'
  23. def context = SSLContext.getInstance('SSL')
  24. def trustManager = [ // サーバ証明書の署名を確認しない X509TrustManager
  25. checkClientTrusted: { chain, authType -> },
  26. checkServerTrusted: { chain, authType -> },
  27. getAcceptedIssuers: {}
  28. ] as X509TrustManager
  29. context.init null, [trustManager] as TrustManager[], null // サーバ証明書の署名を確認しない
  30. connection.SSLSocketFactory = context.socketFactory
  31. connection.hostnameVerifier = { true } as HostnameVerifier // サーバ証明書の発行先を確認しない
  32. connection.inputStream.withStream { input ->
  33. new File('index.html').withOutputStream { it << input }
  34. }
  35. } finally {
  36. connection.disconnect()
  37. }
Apache HttpClient 4.xを使った場合
  1. // import java.io.File
  2. // import javax.net.ssl.*
  3. // import org.apache.http.*
  4. // import org.apache.http.auth.*
  5. // import org.apache.http.client.ResponseHandler
  6. // import org.apache.http.client.methods.HttpGet
  7. // import org.apache.http.conn.params.ConnRoutePNames
  8. // import org.apache.http.conn.scheme.Scheme
  9. // import org.apache.http.conn.ssl.SSLSocketFactory
  10. // import org.apache.http.impl.client.*
  11. // import org.apache.http.params.CoreConnectionPNames
  12. def client = new DefaultHttpClient()
  13. def params = client.params
  14. params.setParameter ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80)
  15. params.setParameter CoreConnectionPNames.CONNECTION_TIMEOUT, 5000 // 5秒でタイムアウトにする
  16. params.setParameter CoreConnectionPNames.SO_TIMEOUT, 5000 // 5秒でタイムアウトにする
  17. def credsProvider = new BasicCredentialsProvider()
  18. credsProvider.setCredentials new AuthScope("proxy.***.ne.jp", 80),
  19. new UsernamePasswordCredentials("proxyUserName", "proxyPassword")
  20. credsProvider.setCredentials new AuthScope("www.***.ne.jp", 443),
  21. new UsernamePasswordCredentials("wwwUserName", "wwwPassword")
  22. client.credentialsProvider = credsProvider
  23. def context = SSLContext.getInstance('SSL')
  24. def trustManager = [ // サーバ証明書の署名を確認しない X509TrustManager
  25. checkClientTrusted: { chain, authType -> },
  26. checkServerTrusted: { chain, authType -> },
  27. getAcceptedIssuers: {}
  28. ] as X509TrustManager
  29. context.init null, [trustManager] as TrustManager[], null // サーバ証明書の署名を確認しない
  30. def socketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
  31. client.connectionManager.schemeRegistry.register new Scheme("https", 443, socketFactory)
  32. def get = new HttpGet("https://www.***.ne.jp/")
  33. get.setHeader "User-Agent", "Mozilla/4.0"
  34. client.execute get, new ResponseHandler() {
  35. @Override def handleResponse(HttpResponse response) {
  36. def statusLine = response.statusLine
  37. switch (statusLine.statusCode) {
  38. case HttpStatus.SC_OK:
  39. new File("index.html").withOutputStream { response.entity.writeTo it }
  40. return
  41. default:
  42. throw new IOException(statusLine.toString())
  43. }
  44. }
  45. }

Scala

  1. // import java.io._
  2. // import java.net._
  3. // import java.security._
  4. // import java.security.cert._
  5. // import javax.net.ssl._
  6. // サーバ証明書の発行先を確認しない HostnameVerifier
  7. class IrresponsibleHostnameVerifier extends HostnameVerifier {
  8. override def verify(hostname: String, session: SSLSession) = true
  9. }
  10. // サーバ証明書の署名を確認しない X509TrustManager
  11. class IrresponsibleX509TrustManager extends X509TrustManager {
  12. override def checkClientTrusted(chain: Array[X509Certificate], authType: String) {}
  13. override def checkServerTrusted(chain: Array[X509Certificate], authType: String) {}
  14. override val getAcceptedIssuers = null
  15. }
  16. // Java の try-with-resources 構文を真似た関数
  17. def tryWith[A <: {def close()}, B](a: A)(f: A => B) = try f(a) finally a.close
  1. Authenticator.setDefault(new Authenticator {
  2. import Authenticator.RequestorType._
  3. override def getPasswordAuthentication = getRequestorType match {
  4. case PROXY => new PasswordAuthentication("proxyUserName", "proxyPassword".toCharArray)
  5. case SERVER => new PasswordAuthentication("wwwUserName", "wwwPassword".toCharArray)
  6. }
  7. })
  8. val url = new URL("https://www.***.ne.jp/")
  9. val proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.***.ne.jp", 80))
  10. val connection = url.openConnection(proxy).asInstanceOf[HttpsURLConnection]
  11. try {
  12. connection.setConnectTimeout(5000) // 5秒でタイムアウトにする
  13. connection.setReadTimeout(5000) // 5秒でタイムアウトにする
  14. connection.setRequestProperty("User-Agent", "Mozilla/4.0")
  15. val context = SSLContext.getInstance("SSL")
  16. context.init(null, Array(new IrresponsibleX509TrustManager), null) // サーバ証明書の署名を確認しない
  17. connection.setSSLSocketFactory(context.getSocketFactory)
  18. connection.setHostnameVerifier(new IrresponsibleHostnameVerifier) // サーバ証明書の発行先を確認しない
  19. tryWith (connection.getInputStream) { in =>
  20. tryWith (new FileOutputStream("index.html")) { out =>
  21. in.transferTo(out)
  22. }
  23. }
  24. } finally {
  25. connection.disconnect
  26. }
Dispatchscala-io を使った場合
  1. // import java.net._
  2. // import java.security.cert.X509Certificate
  3. // import javax.net.ssl._
  4. // import org.apache.http.HttpHost
  5. // import org.apache.http.auth._
  6. // import org.apache.http.auth.params.AuthPNames
  7. // import org.apache.http.client.params.AuthPolicy
  8. // import org.apache.http.conn.params.ConnRoutePNames
  9. // import org.apache.http.conn.scheme.Scheme
  10. // import org.apache.http.conn.ssl.SSLSocketFactory
  11. // import org.apache.http.impl.client._
  12. // import org.apache.http.params.CoreConnectionPNames
  13. // import dispatch._
  14. // import scalax.io.JavaConverters._
  15. // import scalax.file.Path
  16. // サーバ証明書の署名を確認しない X509TrustManager
  17. class IrresponsibleX509TrustManager extends X509TrustManager {
  18. override def checkClientTrusted(chain: Array[X509Certificate], authType: String) {}
  19. override def checkServerTrusted(chain: Array[X509Certificate], authType: String) {}
  20. override val getAcceptedIssuers = null
  21. }
  1. val http = new Http
  2. val client = http.client.asInstanceOf[DefaultHttpClient]
  3. val params = client.getParams
  4. params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("proxy.***.ne.jp", 80))
  5. params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000) // 5秒でタイムアウトにする
  6. params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) // 5秒でタイムアウトにする
  7. val credsProvider = new BasicCredentialsProvider
  8. credsProvider.setCredentials(new AuthScope("proxy.***.ne.jp", 80),
  9. new UsernamePasswordCredentials("proxyUserName", "proxyPassword"))
  10. credsProvider.setCredentials(new AuthScope("www.***.ne.jp", 443),
  11. new UsernamePasswordCredentials("wwwUserName", "wwwPassword"))
  12. client.setCredentialsProvider(credsProvider)
  13. val context = SSLContext.getInstance("SSL")
  14. context.init(null, Array(new IrresponsibleX509TrustManager), null) // サーバ証明書の署名を確認しない
  15. val socketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) // サーバ証明書の発行先を確認しない
  16. client.getConnectionManager.getSchemeRegistry.register(new Scheme("https", 443, socketFactory))
  17. val headers = Map("User-Agent" -> "Mozilla/4.0")
  18. http(url("https://www.***.ne.jp/") <:< headers >> { _.asInput copyDataTo Path("index.html") })

PowerShell

  1. $proxy = New-Object System.Net.WebProxy (New-Object System.Uri http://proxy.***.ne.jp)
  2. $proxy.Credentials = New-Object System.Net.NetworkCredential proxyUserName, proxyPassword
  3. $request = [System.Net.WebRequest]::Create("https://www.***.ne.jp/")
  4. $request.Proxy = $proxy
  5. $request.Timeout = 5000
  6. $request.ReadWriteTimeout = 5000
  7. $request.UserAgent = "Mozilla/4.0"
  8. $request.Credentials = New-Object System.Net.NetworkCredential wwwUserName, wwwPassword
  9. # サーバ証明書の署名も発行先も確認しない
  10. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
  11. $response = $request.GetResponse()
  12. &{
  13. switch ($response.StatusCode) {
  14. 'OK' {
  15. $responseStream = $response.GetResponseStream()
  16. &{
  17. $fileStream = New-Object System.IO.FileStream index.html, OpenOrCreate
  18. &{
  19. $buf = New-Object byte[] 1024
  20. for (;;) {
  21. $count = $responseStream.Read($buf, 0, $buf.Length)
  22. if ($count -le 0) { break }
  23. $fileStream.Write($buf, 0, $count)
  24. }
  25. $fileStream.Close()
  26. trap { $fileStream.Close(); break }
  27. }
  28. $responseStream.Close()
  29. trap { $responseStream.Close(); break }
  30. }
  31. }
  32. }
  33. $response.Close()
  34. trap { $response.Close(); break }
  35. }

F#

  1. // open System.IO
  2. // open System.Net
  3. let proxy = new WebProxy(new System.Uri "http://proxy.***.ne.jp")
  4. proxy.Credentials <- new NetworkCredential("proxyUserName", "proxyPassword")
  5. let request = WebRequest.Create "https://www.***.ne.jp/" :?> HttpWebRequest
  6. request.Proxy <- proxy
  7. request.Timeout <- 5000
  8. request.ReadWriteTimeout <- 5000
  9. request.UserAgent <- "Mozilla/4.0"
  10. request.Credentials <- new NetworkCredential("wwwUserName", "wwwPassword")
  11. // サーバ証明書の署名も発行先も確認しない
  12. ServicePointManager.ServerCertificateValidationCallback <- fun _ _ _ _ -> true
  13. use response = request.GetResponse() :?> HttpWebResponse
  14. match response.StatusCode with
  15. | HttpStatusCode.OK ->
  16. use responseStream = response.GetResponseStream()
  17. use fileStream = new FileStream("index.html", FileMode.OpenOrCreate)
  18. let buf = Array.zeroCreate<byte> 1024
  19. let rec readWrite() =
  20. let count = responseStream.Read(buf, 0, buf.Length)
  21. if count > 0 then
  22. fileStream.Write(buf, 0, count)
  23. readWrite()
  24. readWrite()
  25. | _ -> ()

C#

  1. // using System.IO;
  2. // using System.Net;
  3. var proxy = new WebProxy(new Uri("http://proxy.***.ne.jp"));
  4. proxy.Credentials = new NetworkCredential("proxyUserName", "proxyPassword");
  5. var request = (HttpWebRequest)WebRequest.Create("https://www.***.ne.jp/");
  6. request.Proxy = proxy;
  7. request.Timeout = 5000;
  8. request.ReadWriteTimeout = 5000;
  9. request.UserAgent = "Mozilla/4.0";
  10. request.Credentials = new NetworkCredential("wwwUserName", "wwwPassword");
  11. // サーバ証明書の署名も発行先も確認しない
  12. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
  13. using (var response = (HttpWebResponse)request.GetResponse()) {
  14. switch (response.StatusCode) {
  15. case HttpStatusCode.OK:
  16. using (var responseStream = response.GetResponseStream()) {
  17. using (var fileStream = new FileStream("index.html", FileMode.OpenOrCreate)) {
  18. var buf = new byte[1024];
  19. int count;
  20. while ((count = responseStream.Read(buf, 0, buf.Length)) > 0) {
  21. fileStream.Write(buf, 0, count);
  22. }
  23. }
  24. }
  25. break;
  26. }
  27. }

Ruby

  1. # require 'net/https'
  2. http = Net::HTTP.new 'www.***.ne.jp', 443, 'proxy.***.ne.jp', 80, 'proxyUserName', 'proxyPassword'
  3. http.use_ssl = true
  4. http.verify_mode = OpenSSL::SSL::VERIFY_NONE # サーバ証明書の署名を確認できなくても処理を続行する
  5. http.open_timeout = 5
  6. http.read_timeout = 5
  7. request = Net::HTTP::Get.new '/'
  8. request.basic_auth 'wwwUserName', 'wwwPassword'
  9. request['User-Agent'] = 'Mozilla/4.0'
  10. verbose = $VERBOSE
  11. $VERBOSE = nil # サーバ証明書についての警告が出ないようにする
  12. begin
  13. http.request request do |response|
  14. open 'index.html', 'wb' do |file|
  15. response.read_body {|chunk| file.write chunk }
  16. end
  17. end
  18. ensure
  19. $VERBOSE = verbose
  20. end

Python

  1. # from urllib.request import build_opener
  2. # from urllib.request import HTTPBasicAuthHandler
  3. # from urllib.request import HTTPPasswordMgrWithDefaultRealm
  4. # from urllib.request import ProxyBasicAuthHandler
  5. # from urllib.request import ProxyHandler
  6. proxy_h = ProxyHandler({'https': 'http://proxy.***.ne.jp'})
  7. proxy_auth_h = ProxyBasicAuthHandler(HTTPPasswordMgrWithDefaultRealm())
  8. proxy_auth_h.add_password(None, 'http://proxy.***.ne.jp', 'proxyUserName', 'proxyPassword')
  9. auth_h = HTTPBasicAuthHandler(HTTPPasswordMgrWithDefaultRealm())
  10. auth_h.add_password(None, 'https://www.***.ne.jp/', 'wwwUserName', 'wwwPassword')
  11. opener = build_opener(proxy_h, proxy_auth_h, auth_h)
  12. opener.addheaders = [('User-Agent', 'Mozilla/4.0')]
  13. response = opener.open('https://www.***.ne.jp/', None, 5)
  14. try:
  15. with open('index.html', 'wb') as f:
  16. while True:
  17. bytes = response.read(1024)
  18. if len(bytes) == 0:
  19. break
  20. f.write(bytes)
  21. finally:
  22. response.close()

PHP

  1. $ch = curl_init('https://www.***.ne.jp/');
  2. $f = fopen('index.html', 'w');
  3. curl_setopt_array($ch, [
  4. CURLOPT_FILE => $f,
  5. CURLOPT_TIMEOUT => 5,
  6. CURLOPT_FAILONERROR => TRUE,
  7. CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
  8. CURLOPT_USERPWD => 'wwwUserName:wwwPassword',
  9. CURLOPT_PROXY => 'http://proxy.***.ne.jp',
  10. CURLOPT_PROXYAUTH => CURLAUTH_BASIC,
  11. CURLOPT_PROXYUSERPWD => 'proxyUserName:proxyPassword',
  12. CURLOPT_SSL_VERIFYPEER => FALSE, // サーバ証明書の署名を確認しない
  13. CURLOPT_SSL_VERIFYHOST => 0, // サーバ証明書の発行先を確認しない
  14. CURLOPT_USERAGENT => 'Mozilla/4.0'
  15. ]);
  16. $error = curl_exec($ch) === FALSE ? curl_error($ch) : NULL;
  17. curl_close($ch);
  18. flose($f);
  19. if ($error !== NULL) {
  20. unlink('index.html');
  21. throw new Exception($error);
  22. }

Perl

  1. # use LWP::UserAgent;
  2. $ENV{HTTPS_PROXY} = 'http://proxy.***.ne.jp';
  3. $ENV{HTTPS_PROXY_USERNAME} = 'proxyUserName';
  4. $ENV{HTTPS_PROXY_PASSWORD} = 'proxyPassword';
  5. my $request = HTTP::Request->new('GET', 'https://www.***.ne.jp/');
  6. $request->authorization_basic('wwwUserName', 'wwwPassword');
  7. my $ua = LWP::UserAgent->new(agent => 'Mozilla/4.0', timeout => 5);
  8. $ua->env_proxy;
  9. my $response = $ua->request($request, 'index.html');
  10. unless ($response->is_success) {
  11. unlink 'index.html';
  12. die $response->request->uri . ': ' . $response->status_line;
  13. }

戻る

目次

ディレクトリの直下にあるファイルとサブディレクトリの名前を出力する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
指定されたディレクトリ配下の全てのファイルのリストを取得する関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
テキストファイルの内容を読み出し、行番号を付けて別のファイルに書き出す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
CSVファイルを読み込み、1列目の数値の昇順で別のファイルに出力する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
CSVのパーサを自作する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
読み込んだファイルのMD5値を求め、16進の文字列で表す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
XHTMLのファイルを読み込んで解析する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
JSONデータを解析する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
HTTP でテキストデータを GET する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
HTTP でフォームデータを POST する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
HTTPS でファイルをダウンロードする Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl