永发信息网

Java作业,求帮助,万分感谢🙏

答案:2  悬赏:0  手机版
解决时间 2021-01-30 05:30
  • 提问者网友:皆是孤独
  • 2021-01-29 20:02
Java作业,求帮助,万分感谢🙏
最佳答案
  • 五星知识达人网友:孤老序
  • 2021-01-29 21:28
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;

public class Test {
public static void main(String[] args) throws Exception {
String filePath = "C:\Users\Administrator.PC-20171008FXZS\Desktop\log.txt";
File file = new File(filePath);
readByFileInputStream(file);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
readByBuffer(file);
}

public static void readByFileInputStream(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b))!=-1) {
System.out.println(new String(b,0,i));  
}
fis.close();
}

public static void readByBuffer(File file) throws Exception {
BufferedReader in = new BufferedReader(new FileReader(file));
String s = null;
while((s=in.readLine())!=null) {
System.out.println(s);  
}
in.close();
}
}追问两种方法?从哪儿断开?请问这是一种方法。?
全部回答
  • 1楼网友:雾月
  • 2021-01-29 22:11
这个很简单啊,现在还需要写?追问要写,帮帮忙追答
public static void main(String[] args) {
//writeToTxt();
//readByBuffered();
writeByBuffered();
}
public static void writeToTxt() {
FileOutputStream fos=null;
File file = new File ("F://test.txt");
try {
fos = new FileOutputStream(file);
for(int i=0;i<100;i++) {
fos.write(("hello"+i).getBytes());
fos.write(" ".getBytes());
fos.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readFromTxt() {
File file = new File("F://test.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int i = 0;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readByBuffered() {
File file = new File("F://test.txt");
BufferedInputStream bfis = null;
try {
bfis = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int tmp = 0;
while ((tmp = bfis.read()) != -1) {
System.out.print((char) tmp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bfis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeByBuffered() {
BufferedOutputStream bfos = null;
File file = new File("F://test.txt");
try {
bfos = new BufferedOutputStream(new FileOutputStream(file));
for (int i = 0; i < 100; i++) {
bfos.write(("hello" + i).getBytes());
bfos.write(" ".getBytes());
bfos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bfos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯