java 当多行作为 JTextarea 的输入时,如何在文件中写入多行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10535395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:28:26  来源:igfitidea点击:

How to write multiple lines in a file when this multiple lines take as a input from a JTextarea?

javaswingfilefile-iojtextarea

提问by Animesh Kumar Paul

I take multiple lines as a input from a JTextarea, If I write it in a file, then I get that the multiple lines are write in a one line in file

我将多行作为 JTextarea 的输入,如果我把它写在一个文件中,那么我得到多行写在文件的一行中

Examples:

例子:

In JTextArea:

在 JTextArea 中:

I
am
a
student

Means: variable.text="I'\n'am'\n'a'\n'student"; When I write the string s in file I get:

意思是:variable.text="I'\n'am'\n'a'\n'student"; 当我在文件中写入字符串 s 时,我得到:

I am a student

But I want that the file will contain the same things as I give as a input means--->

但我希望该文件将包含与我作为输入方式提供的相同内容--->

I
am
a
student

This is the code of writing a file :

这是写文件的代码:

      BufferedWriter out = new BufferedWriter(
       new OutputStreamWriter(
                  new FileOutputStream(file), "UTF16"));
      int size=1;
      for(Tableclass variable:tablevector)
      {
            out.write(variable.Text); 
            out.newLine();
            size++;

      }
      out.close();

采纳答案by sfrj

Slighty better version would be :

稍微好一点的版本是:

    try {
        PrintWriter fstream = new PrintWriter(new FileWriter("log.txt"));
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


 for(String word : jTextAreaName.getText().split("\n"))  {    
    fstream.println(word); 
} 
     fstream.flush();

回答by ChadNC

Use out.newLine();

使用 out.newLine();

   BufferedWriter out = new BufferedWriter( 
   new OutputStreamWriter( 
              new FileOutputStream(file), "UTF16")); 
  int size=1; 
  for(Tableclass variable:tablevector) 
  { 
        out.write(variable.Text); 
        out.newLine();          
        size++; 

  } 
  out.close(); 

回答by Dilip Godhani

find this char in your string char(10) or char(13)

在你的字符串 char(10) 或 char(13) 中找到这个字符

int index = textarea.firstIndexOf(CHAR(10));