加入收藏 | 设为首页 | 会员中心 | 我要投稿 广州站长网 (https://www.020zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

java读写php文件,Java 读写文件示例

发布时间:2023-01-05 05:01:49 所属栏目:PHP教程 来源:未知
导读: import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test4 {
public static void main(String[] args) {
FileUtil f = new FileUtil()

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

public class Test4 {

public static void main(String[] args) {

FileUtil f = new FileUtil();

System.out.println(f.read("c:/a.txt"));

final String fileName = "c:/a.txt";

System.out.println(f.delete(fileName));

System.out.println(f.write(fileName,"这是java写入的内容1"));

System.out.println(f.append(fileNamePHP文件, "这是java写入的内容2"));

System.out.println(f.write(fileName, "这是java写入的内容3"));

}

}

/**

* 文件读写类

*/

class FileUtil {

/*

* 删除文件

*/

public boolean delete(String fileName) {

boolean result = false;

File f = new File(fileName);

if (f.exists()) {

try {

result = f.delete();

} catch (Exception e) {

e.printStackTrace();

}

} else {

result = true;

}

return result;

}

/*

* 读取文件

*/

public String read(String fileName) {

File f = new File(fileName);

if (!f.exists()) {

return "File not found!";

}

FileInputStream fs;

String result = null;

try {

fs = new FileInputStream(f);

byte[] b = new byte[fs.available()];

fs.read(b);

fs.close();

result = new String(b);

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

/*

*写文件

*/

public boolean write(String fileName, String fileContent) {

boolean result = false;

File f = new File(fileName);

try {

FileOutputStream fs = new FileOutputStream(f);

byte[] b = fileContent.getBytes();

fs.write(b);

fs.flush();

fs.close();

result = true;

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

/*

* 追加内容到文件

*/

public boolean append(String fileName, String fileContent) {

boolean result = false;

File f = new File(fileName);

try {

if (f.exists()) {

FileInputStream fsIn = new FileInputStream(f);

byte[] bIn = new byte[fsIn.available()];

fsIn.read(bIn);

String oldFileContent = new String(bIn);

//System.out.println("旧内容:" + oldFileContent);

fsIn.close();

if (!oldFileContent.equalsIgnoreCase("")) {

fileContent = oldFileContent + "\r\n" + fileContent;

//System.out.println("新内容:" + fileContent);

}

}

FileOutputStream fs = new FileOutputStream(f);

byte[] b = fileContent.getBytes();

fs.write(b);

fs.flush();

fs.close();

result = true;

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

}

(编辑:广州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!