简体   繁体   English

如何使用打印流

[英]How to use printStream

I have created a few methods to edit text from a file word by word but now need to use printStream to create a new file with the updated text.我创建了一些方法来逐字编辑文件中的文本,但现在需要使用 printStream 创建一个包含更新文本的新文件。 I have done some research on printStream but still don't quite understand how to do this.我对 printStream 做了一些研究,但仍然不太明白如何做到这一点。 Here is my code:这是我的代码:

public static void main(String[] args) throws FileNotFoundException {
    File jaws = new File("JawsScript.txt");
    Scanner in = new Scanner(jaws);


        while (in.hasNext()) {
    String word = in.next();

        PrintStream out =
    new PrintStream(new File("stuff.txt"));

    System.out.println(convert(word));

    } 

The method "convert" is a method that calls all of the other methods and applies all of the changes to a single string in the text:方法“convert”是一种调用所有其他方法并将所有更改应用于文本中单个字符串的方法:

//Applies all of the methods to the string
public static String convert(String s) {
  String result = "";
    result = rYah(s);
    result = rWah(result);
    result = transform(result);
    result = apend(result);
    result = replace(result);

    return result;
}

I basically am just wondering how I can use printStream to apply "convert" to the text and print the updated text to a new file.我基本上只是想知道如何使用 printStream 将“转换”应用于文本并将更新的文本打印到新文件。

First of all, don't reinitialize the PrintStream object in every loop iteration.首先,不要在每次循环迭代中重新初始化 PrintStream 对象。

To write to a file, simply call PrintStream's println method.要写入文件,只需调用 PrintStream 的println方法。 You may not realise it, but when you print to the console, this is exactly what you are doing.您可能没有意识到,但是当您打印到控制台时,这正是您正在做的。 System.out is a PrintStream object. System.out是一个 PrintStream 对象。

PrintStream out =
    new PrintStream(new File("stuff.txt"));
while (in.hasNext()) {
    String word = in.next();
    out.println(convert(word));
}
import java.io.PrintStream;

public class Main2{
    public static void main(String[]args){
        String str = " The Big House is";
        PrintStream ps = new PrintStream(System.out);
        ps.printf("My name is : %s White", str);
        ps.flush();
        ps.close();
    }
}

Output is : The Big House is White输出是:大房子是白色的

The other way to use PrintStream is...使用 PrintStream 的另一种方法是...

        CharSequence cq = "The Big House is White";
        PrintStream ps = new PrintStream(System.out);
        ps.append(cq);
        ps.flush();
        ps.close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM