这是我的代码,我尝试将数据(Ime-name,Pasma-breed,Starost-age,Teza-weight)写入arraylist然后从数组列表到.txt文件。它必须为5只狗(Pes)做,所以我已经习惯了我希望是否有人可以检查它并给我一个反馈。写入数组列表然后写入.txt文件时遇到问题。
谢谢:)
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
class Pes {
private String Ime;
private String Pasma;
private int Starost;
private double Teza;
public void setIme(String Ime) {
this.Ime = Ime;
}
public String getIme() {
return Ime;
}
public void setPasma(String Pasma) {
this.Pasma = Pasma;
}
public String getPasma() {
return Pasma;
}
public void setStarost(int Starost) {
this.Starost = Starost;
}
public int getStarost() {
return Starost;
}
public void setTeza(double Teza) {
this.Teza = Teza;
}
public double getTeza() {
return Teza;
}
Pes() {
Ime = "";
Pasma = "";
Starost = 0;
Teza = 0;
}
}
public class Aplikacija {
public static void main(String[] args) {
new File("Psi.txt");
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 5; i++) {
System.out.println("Vpišite ime!");
String Ime = input.nextLine();
System.out.println("Vpišite pasmo!");
String Pasma = input.nextLine();
System.out.println("Izberite starost!");
int Starost = input.nextInt();
System.out.println("Izberite tezo!");
double Teza = input.nextDouble();
Pes Pes1 = new Pes();
Pes1.setIme(Ime);
Pes1.setPasma(Pasma);
Pes1.setStarost(Starost);
Pes1.setTeza(Teza);
new ArrayList<Pes>();
Pes1.add(new Pes(Ime, Pasma, Starost, Teza));
input.close();
}
FileWriter writer = new FileWriter("Psi.txt");
for (String str : arr) {
writer.write(str);
}
writer.close();
}
}
答案 0 :(得分:1)
您需要使用BufferedWriter
FileWriter writer = new FileWriter("Psi.txt");
BufferedWriter bw = new BufferedWriter(writer);
for (String str : arr) {
bw.write(str);
}
writer.close(); // or use try-with-resources if you use Java SE 7
bw.close();
例如,请参阅How to write in file教程。
或者您可以使用PrintWriter
,这在您的情况下更简单。
PrintWriter writer = new PrintWriter("psi.txt", "UTF-8");
for (String str : arr) {
writer.println(str);
}
writer.close();
答案 1 :(得分:0)
试一试:
import java.io.*;
class class_Name
{
//your code
try
{
File file = new File("../filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(fw);
for (String str : arr)
{
writer.write(str);
}
}
catch(Exception e)
{
e.printstackTrace();
}
}// end of Class