gpt4 book ai didi

java - 解析字符串输出到文件

转载 作者:行者123 更新时间:2023-12-02 08:03:48 24 4
gpt4 key购买 nike

这个“弗兰肯斯坦式”Java 的第一部分工作得很好,但是第二部分输出了一些困惑的废话。所以结果变量将是我来自用户的输入。由于一些愚蠢的原因,在进行解析之前,我必须先将字符串大写,当您来自数据库/分析背景并且知道您在几秒钟内完成某些操作并且不会出现错误时,这很难...我在应得的信用处给予了信用在代码中...

myfile.txt ---> [Ljava.lang.String;@19821f

  import java.io.*;
/*http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29*/

public class StringParser {

public static void main (String arg[])
throws FileNotFoundException {
String result = "eggs toast bacon bacon butter ice beer".toUpperCase();
String[] resultU = result.split("\\s");
String[] y = resultU;

{
for (int x=0; x< resultU.length; x++)



System.out.println(resultU[x]);


/*http://www.javacoffeebreak.com/java103/java103.html#output*/

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println (resultU);

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
}

最佳答案

您是否意识到您正在为数组中的每个元素覆盖同一个文件?

你应该使用

out = new FileOutputStream("myfile.txt", true); // appends to existing file

以及打印实际元素,而不是整个数组的字符串表示形式

p.println(resultU[x]);  // resultU without index prints the whole array - yuk!

尽管您可能应该更新代码以仅创建输出文件一次并将数组的每个元素写入同一输出流,因为当前方法效率有点低。

类似于

public static void main(String[] args) {

String result = "eggs toast bacon bacon butter ice beer".toUpperCase();

PrintStream p = null;

try {
p = new PrintStream(new FileOutputStream("myfile.txt"));

for (String s : result.split("\\s")) {
p.println(s);
p.flush(); // probably not necessary
}

} catch (Exception e) {
e.printStackTrace(); // should really use a logger instead!
} finally {
try {
p.close(); // wouldn't need this in Java 7!
} catch (Exception e) {
}
}
}

关于java - 解析字符串输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8483705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com