每种编程语言的文件I / O

这是所有程序员不时遇到的常见问题。 如何从文本文件读取一行? 那么下一个问题总是如何写回来。

当然,你们大多数人在日常编程中使用高级框架(在答案中可以很好地使用),但是有时候也很高兴知道如何在低级别上做到这一点。

我自己也知道如何在CC++Objective-C做到这一点,但是如果只是为了帮助我们更好地决定使用什么语言来完成我们的文件io in。特别是我认为看看它是如何在string操作语言中完成的,比如: pythonruby ,当然还有perl

所以我想这里我们可以创build一个社区资源 ,当我们需要用某种新语言做文件I / O的时候,我们可以把它们全部加载到我们的configuration文件中。 更不用说我们将接触到的语言,我们不会每天都处理。

这是你如何回答:

  1. 创build一个名为“ fileio.txt ”的新文本文件
  2. 将第一行“hello”写入文本文件。
  3. 将第二行“世界”追加到文本文件中。
  4. 将第二行“world”读入inputstring。
  5. 将inputstring打印到控制台。

澄清:

  • 你应该只显示一个编程语言如何做到这一点。
  • 假定文本文件不存在
  • 写完第一行后,不需要重新打开文本文件

语言没有特别的限制。 CC++C#JavaObjective-C都很棒。

如果你知道如何在PrologHaskellFortranLispBasic做到这一点,那么请继续前进。

Python 3

 with open('fileio.txt', 'w') as f: f.write('hello') with open('fileio.txt', 'a') as f: f.write('\nworld') with open('fileio.txt') as f: s = f.readlines()[1] print(s) 

澄清

  • readlines()返回文件中所有行的列表 。 因此,调用readlines()会导致读取文件的每一行。 在这种情况下,使用readlines()是很好的,因为我们必须读取整个文件(我们希望它的最后一行)。 但是如果我们的文件包含很多行,而我们只想打印它的第n行,则不需要读取整个文件。 这里有一些更好的方法来获取Python中的第n行文件: 在Python 3中用什么替代xreadlines()? 。

  • 这是什么声明? with语句将启动一个代码块,您可以在其中使用variablesf作为从调用open()返回的stream对象 。 当with块结束时,python会自动调用f.close()。 这可以确保无论退出块如何或何时(即使通过未处理的exception退出),退出with块时文件都将被closures。 你可以明确地调用f.close(),但是如果你的代码引发了一个exception,并且你没有得到f.close()调用呢? 这就是为什么with语句是有用的。

  • 每次操作之前,您不需要重新打开文件。 你可以把整个代码写在一个块中。

     with open('fileio.txt', 'w+') as f: f.write('hello') f.write('\nworld') s = f.readlines()[1] print(s) 

    我使用三个块来模仿三个操作之间的区别:写入(模式'w'),追加(模式'a'),读取(模式'r',默认)。

LOLCODE

规范是粗略的说至less,但我尽我所能。 让downvoting开始吧! :)我仍然觉得这是一个有趣的练习。

 HAI CAN HAS STDIO? PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"? AWSUM THX BTW #There is no standard way to output to files yet... VISIBLE "Hello" ON TehFilez BTW #There isn't a standard way to append to files either... MOAR VISIBLE "World" ON TehFilez GIMMEH LINES TehLinez OUTTA TehFilez I HAS A SecondLine ITZ 1 IN MAH TehLinez VISIBLE SecondLine O NOES VISIBLE "OH NOES!!!" KTHXBYE 

脑***ķ

 ,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>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]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]] 

COBOL

由于没有其他人……

 IDENTIFICATION DIVISION. PROGRAM-ID. WriteDemo. AUTHOR. Mark Mullin. * Hey, I don't even have a cobol compiler ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD TestFile. 01 TestData. 02 LineNum PIC X. 02 LineText PIC X(72). PROCEDURE DIVISION. Begin. OPEN OUTPUT TestFile DISPLAY "This language is still around." PERFORM GetFileDetails PERFORM UNTIL TestData = SPACES WRITE TestData PERFORM GetStudentDetails END-PERFORM CLOSE TestFile STOP RUN. GetFileDetails. DISPLAY "Enter - Line number, some text" DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ACCEPT TestData. 

哈斯克尔

 main :: IO () main = let filePath = "fileio.txt" in do writeFile filePath "hello" appendFile filePath "\nworld" fileLines <- readFile filePath let secondLine = (lines fileLines) !! 1 putStrLn secondLine 

如果你只是想读/写一个文件:

 main :: IO () main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 

d

 module d_io; import std.stdio; void main() { auto f = File("fileio.txt", "w"); f.writeln("hello"); f.writeln("world"); f.open("fileio.txt", "r"); f.readln; auto s = f.readln; writeln(s); } 

ruby

 PATH = 'fileio.txt' File.open(PATH, 'w') { |file| file.puts "hello" } File.open(PATH, 'a') { |file| file.puts "world" } puts line = File.readlines(PATH).last 

C#

 string path = "fileio.txt"; File.WriteAllLines(path, new[] { "hello"}); //Will end it with Environment.NewLine File.AppendAllText(path, "world"); string secondLine = File.ReadLines(path).ElementAt(1); Console.WriteLine(secondLine); 

File.ReadLines(path).ElementAt(1)只是.Net 4.0,替代方法是File.ReadAllLines(path)[1]将整个文件parsing成一个数组。

ANSI C

 #include <stdio.h> #include <stdlib.h> int /*ARGSUSED*/ main(char *argv[0], int argc) { FILE *file; char buf[128]; if (!(file = fopen("fileio.txt", "w")) { perror("couldn't open for writing fileio.txt"); exit(1); } fprintf(file, "hello"); fclose(file); if (!(file = fopen("fileio.txt", "a")) { perror("couldn't opened for appening fileio.txt"); exit(1); } fprintf(file, "\nworld"); fclose(file); if (!(file = fopen("fileio.txt", "r")) { perror("couldn't open for reading fileio.txt"); exit(1); } fgets(buf, sizeof(buf), file); fgets(buf, sizeof(buf), file); fclose(file); puts(buf); return 0; } 

Shell脚本(UNIX)

 #!/bin/sh echo "hello" > fileio.txt echo "world" >> fileio.txt LINE=`sed -ne2p fileio.txt` echo $LINE 

其实sed -n "2p"部分打印第二行,但问题要求第二行存储在一个variables,然后打印,所以… 🙂

Linux上的x86汇编程序(NASM)

7年来我没有碰到过,所以我不得不用谷歌一点点来破解这个,但仍然有效;)我知道这不是100%正确的,但嘿:D

好吧,它不起作用。 对不起,这个。 虽然它最终打印world ,但它不是从文件打印,而是从第27行设置的ecx打印。

 section .data hello db 'hello',10 helloLen equ $-hello world db 'world',10 worldLen equ $-world helloFile db 'hello.txt' section .text global _start _start: mov eax,8 mov ebx,helloFile mov ecx,00644Q int 80h mov ebx,eax mov eax,4 mov ecx, hello mov edx, helloLen int 80h mov eax,4 mov ecx, world mov edx, worldLen int 80h mov eax,6 int 80h mov eax,5 mov ebx,helloFile int 80h mov eax,3 int 80h mov eax,4 mov ebx,1 int 80h xor ebx,ebx mov eax,1 int 80h 

使用的参考文献: http : //www.cin.ufpe.br/~if817/arquivos/asmtut/quickstart.html

http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html

http://www.digilife.be/quickreferences/QRC/LINUX%20System%20Call%20Quick%20Reference.pdf

JavaScript – node.js

首先,大量的嵌套callback。

 var fs = require("fs"); var sys = require("sys"); var path = "fileio.txt"; fs.writeFile(path, "hello", function (error) { fs.open(path, "a", 0666, function (error, file) { fs.write(file, "\nworld", null, "utf-8", function () { fs.close(file, function (error) { fs.readFile(path, "utf-8", function (error, data) { var lines = data.split("\n"); sys.puts(lines[1]); }); }); }); }); }); 

有点清洁:

 var writeString = function (string, nextAction) { fs.writeFile(path, string, nextAction); }; var appendString = function (string, nextAction) { return function (error, file) { fs.open(path, "a", 0666, function (error, file) { fs.write(file, string, null, "utf-8", function () { fs.close(file, nextAction); }); }); }; }; var readLine = function (index, nextAction) { return function (error) { fs.readFile(path, "utf-8", function (error, data) { var lines = data.split("\n"); nextAction(lines[index]); }); }; }; var writeToConsole = function (line) { sys.puts(line); }; writeString("hello", appendString("\nworld", readLine(1, writeToConsole))); 

Common Lisp

 (defun main () (with-open-file (s "fileio.txt" :direction :output :if-exists :supersede) (format s "hello")) (with-open-file (s "fileio.txt" :direction :io :if-exists :append) (format s "~%world") (file-position s 0) (loop repeat 2 for line = (read-line s nil nil) finally (print line)))) 

电源shell

 sc fileio.txt 'hello' ac fileio.txt 'world' $line = (gc fileio.txt)[1] $line 

Shell脚本

这是一个使用内置命令的shell脚本,而不是像以前的响应那样调用sedtail类的外部命令。

 #!/bin/sh echo hello > fileio.txt # Print "hello" to fileio.txt echo world >> fileio.txt # Print "world" to fileio.txt, appending # to what is already there { read input; read input; } < fileio.txt # Read the first two lines of fileio.txt, # storing the second in $input echo $input # Print the contents of $input 

在编写重要的shell脚本时,build议尽可能使用builtins,因为产生一个单独的进程可能会很慢; 从我的机器上快速testing, sed解决scheme比使用read要慢20倍左右。 如果你要打电话给sed一次,就像在这种情况下一样,这并不重要,因为它的执行速度会比你注意到的要快,但是如果你要执行它几百或几千次,可以加起来。

对于那些不熟悉语法的人来说, {} 在当前shell环境下执行一系列命令 (而不是()创build一个子shell;我们需要在当前的shell环境下运行,所以我们可以使用之后的variables)。 我们需要将这些命令组合在一起,以使它们都在相同的inputstream上操作,这是通过从fileio.txtredirect创build的; 如果我们只是运行read < fileio.txt; read input < fileio.txt read < fileio.txt; read input < fileio.txt ,我们只会得到第一行,因为文件将被closures,并重新打开这两个命令之间。 由于shell语法的特殊性( {}是保留字,与元字符相反),我们需要使用空格将{}与其余命令分隔开,并用a ;终止命令列表;

read内build需要readvariables的名字作为参数。 它消耗了一行input,以空格分隔input(从技术上说,它根据$IFS的内容来分解它,默认为空格字符,空格字符表示将其分隔在任何空格,制表符或换行符上) ,将每个单词分配给按顺序给定的variables名称,并将该行的其余部分分配给最后一个variables。 由于我们只是提供一个variables,它只是把整个行放在这个variables中。 我们重用$inputvariables,因为我们不关心第一行是什么(如果我们使用Bash,我们可能不提供variables名称,但为了便于携带,您必须始终提供至less一个名称)。

请注意,尽pipe可以一次读取一行,就像我在这里所做的那样,但更常见的模式是将其包装在一个while循环中:

 while read foo bar baz do process $foo $bar $baz done < input.txt 

Clojure的

 (use '[clojure.java.io :only (reader)]) (let [file-name "fileio.txt"] (spit file-name "hello") (spit file-name "\nworld" :append true) (println (second (line-seq (reader file-name))))) 

或者等价地,使用线程macros-> (也被称为paren卸妆):

 (use '[clojure.java.io :only (reader)]) (let [file-name "fileio.txt"] (spit file-name "hello") (spit file-name "\nworld" :append true) (-> file-name reader line-seq second println)) 

F#

 let path = "fileio.txt" File.WriteAllText(path, "hello") File.AppendAllText(path, "\nworld") let secondLine = File.ReadLines path |> Seq.nth 1 printfn "%s" secondLine 

BASIC

近十年来我还没有使用BASIC,但这个问题让我有理由迅速提高自己的知识水平。 🙂

 OPEN "fileio.txt" FOR OUTPUT AS 1 PRINT #1, "hello" PRINT #1, "world" CLOSE 1 OPEN "fileio.txt" FOR INPUT AS 1 LINE INPUT #1, A$ LINE INPUT #1, A$ CLOSE 1 PRINT A$ 

Objective-C的

 NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:@"fileio.txt"]; [[NSFileManager defaultManager] createFileAtPath:@"fileio.txt" contents:nil attributes:nil]; [fh writeData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]]; [fh writeData:[@"\nworld" dataUsingEncoding:NSUTF8StringEncoding]]; NSArray *linesInFile = [[[NSString stringWithContentsOfFile:@"fileio.txt" encoding:NSUTF8StringEncoding error:nil] stringByStandardizingPath] componentsSeparatedByString:@"\n"]; NSLog(@"%@", [linesInFile objectAtIndex:1]); 

Perl的

 #!/usr/bin/env perl use 5.10.0; use utf8; use strict; use autodie; use warnings qw< FATAL all >; use open qw< :std :utf8 >; use English qw< -no_match_vars >; # and the last shall be first END { close(STDOUT) } my $filename = "fileio.txt"; my($handle, @lines); $INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n"; open($handle, ">", $filename); print $handle "hello"; close($handle); open($handle, ">>", $filename); print $handle "world"; close($handle); open($handle, "<", $filename); chomp(@lines = <$handle>); close($handle); print STDOUT $lines[1]; 

R:

猫(“你好\ n”,文件=“fileio.txt”)
 cat(“world \ n”,file =“fileio.txt”,append = TRUE)
 line2 = readLines(“fileio.txt”,n = 2)[2]
猫(2号线)

PHP

 <?php $filePath = "fileio.txt"; file_put_contents($filePath, "hello"); file_put_contents($filePath, "\nworld", FILE_APPEND); $lines = file($filePath); echo $lines[1]; // closing PHP tags are bad practice in PHP-only files, don't use them 

Java的

 import java.io.*; import java.util.*; class Test { public static void main(String[] args) throws IOException { String path = "fileio.txt"; File file = new File(path); //Creates New File... try (FileOutputStream fout = new FileOutputStream(file)) { fout.write("hello\n".getBytes()); } //Appends To New File... try (FileOutputStream fout2 = new FileOutputStream(file,true)) { fout2.write("world\n".getBytes()); } //Reading the File... try (BufferedReader fin = new BufferedReader(new FileReader(file))) { fin.readLine(); System.out.println(fin.readLine()); } } } 

C ++

 #include <limits> #include <string> #include <fstream> #include <iostream> int main() { std::fstream file( "fileio.txt", std::ios::in | std::ios::out | std::ios::trunc ); file.exceptions( std::ios::failbit ); file << "hello\n" // << std::endl, not \n, if writing includes flushing << "world\n"; file.seekg( 0 ) .ignore( std::numeric_limits< std::streamsize >::max(), '\n' ); std::string input_string; std::getline( file, input_string ); std::cout << input_string << '\n'; } 

or somewhat less pedantically,

 #include <string> #include <fstream> #include <iostream> using namespace std; int main() { fstream file( "fileio.txt", ios::in | ios::out | ios::trunc ); file.exceptions( ios::failbit ); file << "hello" << endl << "world" << endl; file.seekg( 0 ).ignore( 10000, '\n' ); string input_string; getline( file, input_string ); cout << input_string << endl; } 

 package main import ( "os" "bufio" "log" ) func main() { file, err := os.Open("fileio.txt", os.O_RDWR | os.O_CREATE, 0666) if err != nil { log.Exit(err) } defer file.Close() _, err = file.Write([]byte("hello\n")) if err != nil { log.Exit(err) } _, err = file.Write([]byte("world\n")) if err != nil { log.Exit(err) } // seek to the beginning _, err = file.Seek(0,0) if err != nil { log.Exit(err) } bfile := bufio.NewReader(file) _, err = bfile.ReadBytes('\n') if err != nil { log.Exit(err) } line, err := bfile.ReadBytes('\n') if err != nil { log.Exit(err) } os.Stdout.Write(line) } 

二郎神

Probably not the most idiomatic Erlang, but:

 #!/usr/bin/env escript main(_Args) -> Filename = "fileio.txt", ok = file:write_file(Filename, "hello\n", [write]), ok = file:write_file(Filename, "world\n", [append]), {ok, File} = file:open(Filename, [read]), {ok, _FirstLine} = file:read_line(File), {ok, SecondLine} = file:read_line(File), ok = file:close(File), io:format(SecondLine). 

Emacs Lisp

Despite what some people say Emacs is mainly a text editor [1]. So while Emacs Lisp can be used to solve all kinds of problems it is optimized towards the needs of a text editor. Since text editors (obviously) have quite specific needs when it comes to how files are handled this affects what file related functionality Emacs Lisp offers.

Basically this means that Emacs Lisp does not offer functions to open a file as a stream, and read it part by part. Likewise you can't append to a file without loading the whole file first. Instead the file is completely [2] read into a buffer [3], edited and then saved to a file again.

For must tasks you would use Emacs Lisp for this is suitable and if you want to do something that does not involve editing the same functions can be used.

If you want to append to a file over and over again this comes with a huge overhead, but it is possible as demonstrated here. In practice you normally finish making changes to a buffer whether manually or programmatically before writing to a file (just combine the first two s-expressions in the example below).

 (with-temp-file "file" (insert "hello\n")) (with-temp-file "file" (insert-file-contents "file") (goto-char (point-max)) (insert "world\n")) (with-temp-buffer (insert-file-contents "file") (next-line) (message "%s" (buffer-substring (point) (line-end-position)))) 

[1] At least I would not go as far as calling it an OS; an alternative UI yes, an OS no.

[2] You can load only parts of a file, but this can only be specified byte-wise.

[3] A buffer is both a datatype in someways similar to a string as well as the "thing you see while editing a file". While editing a buffer is displayed in a window but buffers do not necessarily have to be visible to the user.

Edit: If you want to see the text being inserted into the buffer you obviously have to make it visible, and sleep between actions. Because Emacs normally only redisplays the screen when waiting for user input (and sleeping ain't the same as waiting for input) you also have to force redisplay. This is necessary in this example (use it in place of the second sexp); in practice I never had to use `redisplay' even once – so yes, this is ugly but …

 (with-current-buffer (generate-new-buffer "*demo*") (pop-to-buffer (current-buffer)) (redisplay) (sleep-for 1) (insert-file-contents "file") (redisplay) (sleep-for 1) (goto-char (point-max)) (redisplay) (sleep-for 1) (insert "world\n") (redisplay) (sleep-for 1) (write-file "file")) 

Windows Batch Files – Version #2

 @echo off echo hello > fileio.txt echo world >> fileio.txt set /P answer=Insert: echo %answer% >> fileio.txt for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A 

To explain that last horrible looking for loop, it assumes that there is only hello (newline) world in the file. So it just skips the first line and echos only the second.

更新日志

  • 2 – Opps, must of misread the requirements or they changed on me. Now reads last line from file

Scala:

Using standard library:

 val path = "fileio.txt" val fout = new FileWriter(path) fout write "hello\n" fout.close() val fout0 = new FileWriter(path, true) fout0 write "world\n" fout0.close() val str = Source.fromFile(path).getLines.toSeq(1) println(str) 

Using Josh Suereth's Scala-ARM Library :

 val path = "fileio.txt" for(fout <- managed(new FileWriter(path))) fout write "hello\n" for(fout <- managed(new FileWriter(path, true))) fout write "world\n" val str = Source.fromFile(path).getLines.toSeq(1) println(str) 


Since many people have used the same file descriptor to write the two strings, I'm also including that way in my answer.

Using standard library:

 val path = "fileio.txt" val fout = new FileWriter(path) fout write "hello\n" fout write "world\n" fout.close() val str = Source.fromFile(path).getLines.toSeq(1) println(str) 

Using Josh Suereth's Scala-ARM Library :

 val path = "fileio.txt" for(fout <- managed(new FileWriter(path))){ fout write "hello\n" fout write "world\n" } val str = Source.fromFile(path).getLines.toSeq(1) println(str) 

Groovy的

 new File("fileio.txt").with { write "hello\n" append "world\n" println secondLine = readLines()[1] }