fileoutputstream 写入字符串
时间: 2023-09-14 11:06:27 浏览: 86
可以使用 FileOutputStream 写入字符串,但是需要将字符串转换为 byte 数组再进行写入。可以使用 String 类的 getBytes() 方法将字符串转换为 byte 数组,然后再使用 FileOutputStream 的 write() 方法写入文件。
例如,以下代码将字符串写入到文件中:
```
String str = "Hello, world!";
byte[] bytes = str.getBytes();
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
```
注意,在写入文件时需要考虑字符编码的问题,否则可能会导致乱码。可以在 getBytes() 方法中指定字符编码,例如:
```
byte[] bytes = str.getBytes("UTF-8");
```
相关问题
JAva中fileoutputstream写入文件
在Java中使用FileOutputStream类可以将数据写入文件。下面是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
String data = "Hello, world!";
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用try-with-resources结构打开一个FileOutputStream对象,并将数据写入output.txt文件中。```getBytes```方法将字符串转换为字节数组,这样我们可以将它写入文件。注意,在使用完FileOutputStream对象后,我们不需要显式关闭它,因为try-with-resources结构将自动关闭它。
itextpdf类在pdf指定位置写入字符串
以下是使用itextpdf类在pdf指定位置写入字符串的示例代码:
```java
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.FileOutputStream;
import java.io.IOException;
public class PdfWriterExample {
public static void main(String[] args) {
try {
// 读取原始PDF文件
PdfReader reader = new PdfReader("input.pdf");
// 创建输出PDF文件
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));
// 获取指定页面的内容流
PdfContentByte content = stamper.getOverContent(1);
// 设置字体
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, 12, Font.NORMAL);
// 在指定位置添加文本
content.beginText();
content.setFontAndSize(baseFont, 12);
content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Hello, World!", 100, 100, 0);
content.endText();
// 关闭PDF文件
stamper.close();
reader.close();
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
}
```
这段代码使用itextpdf库来读取原始的PDF文件,并在指定位置添加文本。首先,我们创建一个PdfReader对象来读取原始PDF文件。然后,我们创建一个PdfStamper对象来写入输出PDF文件。通过调用`getOverContent()`方法,我们可以获取指定页面的内容流。接下来,我们设置字体并使用`showTextAligned()`方法在指定位置添加文本。最后,我们关闭PDF文件。
请注意,这只是一个示例代码,你需要根据你的实际需求进行适当的修改。