gpt4 book ai didi

java - 如何用Java编写文件列表

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

我有一个 Java 类,它使用 FileOutputStream 和 BufferedOutputStream 写入文件。这工作正常,但我的意图是我想用 java 编写任意数量的文件,而不仅仅是一个。这是我用 Java 编写的代码

public class FileToBeTaken{


public void fileBack(byte [] output) {

FileOutputStream fop = null;
BufferedOutputStream bos = null;
File file;


try {
file= new File("/Users/user/Desktop/newfile.txt");

fop = new FileOutputStream(file);

bos = new BufferedOutputStream(fop);

// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}



bos.write(output);
bos.flush();
bos.close();

System.out.println("Done");

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

此处 fileBack 方法在 for 循环内从另一个类调用 n 次。因此,每次我需要在桌面上写入一个新文件时,因为我的代码是我只使用最后一次迭代的文件。另外我应该提到,对于每次迭代,作为此类的参数,都会发送一个字节数组,该数组由“byte [] 输出”获取

最佳答案

改变public void fileBack(byte[]输出){

public void fileBack(String fileName, byte[] 输出) {

然后通过在其他类中提供文件名来更改调用方法 fileBack 的位置。即

byte output[] = //You already provide this byte array

String fileName = "/Users/user/Desktop/newfile.txt"

fileBack(fileName, output);

关于java - 如何用Java编写文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173249/

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