使用java将一个文件的输出存储在另一个文件中

时间:2016-06-15 09:27:15

标签: java java-8 fileoutputstream

在此代码中,使用一个文件(new.txt)完成了一些操作 我想将下面代码的输出存储在另一个文件中....

public static void main(String a[]) throws Exception {
    try {
        Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
                .replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
                .split("1003.*?1002")) // split on end-to-start-of-next
                .forEach(System.out::println);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:3)

由于您已将整个文件内容保留在内存中,因此非流解决方案更直接。

finale String EOL = "\n";
txt = txt.replaceAll("^.*?1002|1003(.(?!1002))*$", EOL ) // trim leading/trailing non-data
txt = txt.replaceAll("1003.*?1002", EOL ) // split on end-to-start-of-next

<强> 加了: 虽然逻辑逃避了我,但替换可能应该是:

package controllers

import play.api.libs.mailer._
import java.io.File
import org.apache.commons.mail.EmailAttachment
import javax.inject.Inject
import play.api._
import play.api.mvc._
import scala.concurrent.Future
import play.api.libs.json._

class MailerApi @Inject() (mailerClient: MailerClient) extends Controller {
  def sendEmail = Action.async(parse.json) { request =>
    val subject: String = (request.body \ "subject").as[String]

    val cid = "1234"
    val email = Email(
      subject,
      "Me <email1@gmail.com>",
      Seq("Miss TO email2@gmail.com"),
      // adds attachment
      attachments = Seq(),
      // sends text, HTML or both...
      bodyText = Some("A text message"),
      bodyHtml = Some("content")).addBcc("<email1@gmail.com>")
    mailerClient.send(email)
    Future.successful(Ok("ok !!"))
  }
}

答案 1 :(得分:2)

你可以尝试:

public static void main(String a[]) throws Exception
{
    try {
        PrintWriter os = new PrintWriter("output.txt");
        Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
            .replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
            .split("1003.*?1002"))                        // split on end-to-start-of-next
            .forEachOrdered(os::println);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

不确定你究竟想要什么。这是一种方法,我会做什么 您可以直接从终端

执行此操作
javac myFile.java
java ClassName > myfile.txt

这会将您的输出保存到文件'myfile.txt'