在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
如果您需要基于一个字符串创建文本文件:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
其他回答
只是在我的项目中做了类似的事情。使用FileWriter将简化部分工作。在这里你可以找到很好的教程。
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
使用Java 7:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
使用这个,它非常易读:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
File file = new File( fileName );
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
您可以将此方法插入到类中。如果在具有主方法的类中使用此方法,请通过添加静态关键字将该类更改为static。无论哪种方式,您都需要导入java.io.*以使其正常工作,否则将无法识别File、FileWriter和BufferedWriter。
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});