스칼라 : 한 문장으로 파일에 문자열 쓰기
스칼라에서 파일을 읽으려면
Source.fromFile("file.txt").mkString
문자열을 파일에 쓰는 동등하고 간결한 방법이 있습니까?
대부분의 언어는 그런 것을 지원합니다. 내가 가장 좋아하는 것은 Groovy입니다.
def f = new File("file.txt")
// Read
def s = f.text
// Write
f.text = "file contents"
한 줄에서 짧은 코드 페이지에 이르는 프로그램에 코드를 사용하고 싶습니다. 자신의 라이브러리를 사용해야한다는 것은 여기서 의미가 없습니다. 현대 언어로 파일에 편리하게 무언가를 쓸 수 있기를 기대합니다.
이와 비슷한 게시물이 있지만 정확한 질문에 답하지 않거나 이전 스칼라 버전에 중점을 둡니다.
예를 들면 다음과 같습니다.
간결한 한 줄 :
import java.io.PrintWriter
new PrintWriter("filename") { write("file contents"); close }
아무도 NIO.2 작업을 제안하지 않은 것은 이상합니다 (Java 7부터 사용 가능).
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))
나는 이것이 가장 간단하고 가장 쉽고 관용적 인 방법이라고 생각하며 Java 자체의 종속성이 필요하지 않습니다.
reflect.io.file을 사용하는 간결한 1 라이너는 Scala 2.12와 함께 작동합니다.
reflect.io.File("filename").writeAll("hello world")
또는 Java 라이브러리를 사용하려는 경우 다음 해킹을 수행 할 수 있습니다.
Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}
Groovy 구문이 마음에 들면 Pimp-My-Library 디자인 패턴을 사용하여 Scala로 가져올 수 있습니다.
import java.io._
import scala.io._
class RichFile( file: File ) {
def text = Source.fromFile( file )(Codec.UTF8).mkString
def text_=( s: String ) {
val out = new PrintWriter( file , "UTF-8")
try{ out.print( s ) }
finally{ out.close }
}
}
object RichFile {
implicit def enrichFile( file: File ) = new RichFile( file )
}
예상대로 작동합니다.
scala> import RichFile.enrichFile
import RichFile.enrichFile
scala> val f = new File("/tmp/example.txt")
f: java.io.File = /tmp/example.txt
scala> f.text = "hello world"
scala> f.text
res1: String =
"hello world
import sys.process._
"echo hello world" #> new java.io.File("/tmp/example.txt") !
내가 쓴 마이크로 라이브러리 : https://github.com/pathikrit/better-files
file.write("Hi!")
또는
file << "Hi!"
Apache File Utils를 쉽게 사용할 수 있습니다 . 기능을보십시오 writeStringToFile
. 우리는 프로젝트에서이 라이브러리를 사용합니다.
이것은 간결합니다.
scala> import java.io._
import java.io._
scala> val w = new BufferedWriter(new FileWriter("output.txt"))
w: java.io.BufferedWriter = java.io.BufferedWriter@44ba4f
scala> w.write("Alice\r\nBob\r\nCharlie\r\n")
scala> w.close()
하나는이 형식을 가지고 있으며 간결하고 기본 라이브러리는 아름답게 작성되었습니다 (소스 코드 참조).
import scalax.io.Codec
import scalax.io.JavaConverters._
implicit val codec = Codec.UTF8
new java.io.File("hi-file.txt").asOutput.write("I'm a hi file! ... Really!")
You can do this with a mix of Java and Scala libraries. You will have full control over the character encoding. But unfortunately, the file handles will not be closed properly.
scala> import java.io.ByteArrayInputStream
import java.io.ByteArrayInputStream
scala> import java.io.FileOutputStream
import java.io.FileOutputStream
scala> BasicIO.transferFully(new ByteArrayInputStream("test".getBytes("UTF-8")), new FileOutputStream("test.txt"))
I know it's not one line, but it solves the safety issues as far as I can tell;
// This possibly creates a FileWriter, but maybe not
val writer = Try(new FileWriter(new File("filename")))
// If it did, we use it to write the data and return it again
// If it didn't we skip the map and print the exception and return the original, just in-case it was actually .write() that failed
// Then we close the file
writer.map(w => {w.write("data"); w}).recoverWith{case e => {e.printStackTrace(); writer}}.map(_.close)
If you didn't care about the exception handling then you can write
writer.map(w => {w.writer("data"); w}).recoverWith{case _ => writer}.map(_.close)
UPDATE: I have since created a more effective solution upon which I have elaborated here: https://stackoverflow.com/a/34277491/501113
I find myself working more and more in the Scala Worksheet within the Scala IDE for Eclipse (and I believe there is something equivalent in IntelliJ IDEA). Anyway, I need to be able to do a one-liner to output some of the contents as I get the "Output exceeds cutoff limit." message if I am doing anything significant, especially with the Scala collections.
I came up with a one-liner I insert into the top of each new Scala Worksheet to simplify this (and so I don't have to do the whole external library import exercise for a very simple need). If you are a stickler and notice that it is technically two lines, it's only to make it more readable in this forum. It is a single line in my Scala Worksheet.
def printToFile(content: String, location: String = "C:/Users/jtdoe/Desktop/WorkSheet.txt") =
Some(new java.io.PrintWriter(location)).foreach{f => try{f.write(content)}finally{f.close}}
And the usage is simply:
printToFile("A fancy test string\ncontaining newlines\nOMG!\n")
This allows me to optionally provide the file name should I want to have additional files beyond the default (which completely overwrites the file each time the method is called).
So, the second usage is simply:
printToFile("A fancy test string\ncontaining newlines\nOMG!\n", "C:/Users/jtdoe/Desktop/WorkSheet.txt")
Enjoy!
Through the magic of the semicolon, you can make anything you like a one-liner.
import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
, StandardCharsets.UTF_8
, StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()
참고URL : https://stackoverflow.com/questions/6879427/scala-write-string-to-file-in-one-statement
'IT' 카테고리의 다른 글
HTTP GET 요청에 컨텐츠 유형 헤더가 필요합니까? (0) | 2020.06.27 |
---|---|
__file__ 변수는 무엇을 의미합니까? (0) | 2020.06.27 |
경고-빌드 경로는 실행 환경을 지정합니다. J2SE-1.4 (0) | 2020.06.26 |
CSS : 중간에 텍스트로 원을 그리는 방법은 무엇입니까? (0) | 2020.06.26 |
Java 문자열을 모든 대문자 (밑줄로 분리 된 단어)에서 CamelCase (단어 구분 기호 없음)로 변환하는 가장 간단한 방법은 무엇입니까? (0) | 2020.06.26 |