问题遇到的现象和发生背景
我用BufferedWriter写到文档里面,同时也放到了LinkedList里面去,但是重写启动程序的时候,文档里面有先前输入的数据,可是LinkedList这个集合里面没有
问题相关代码,请勿粘贴截图
package KTV;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class KtvSystem_reborn {
private static String name;//歌曲名字
private static LinkedList<String> music;
public static void main(String[] args) throws IOException{
music=new LinkedList<String>();
//判断文件是否存在
File file = new File("D:\\Music\\music.txt");
if(!file.exists()) {
file.getParentFile().mkdirs();//多级创建
file.createNewFile();
}
KtvSystem_reborn ktv = new KtvSystem_reborn();
ktv.Menu(file);
}
public static void esc() {
// TODO 自动生成的方法存根
}
public static void Menu(File file) throws IOException {
System.out.println("-----欢迎来到KTV点歌系统------");
System.out.println("1.将所选歌曲置顶");
System.out.println("2.将所选歌曲提前一位");
System.out.println("3.添加一首歌曲");
System.out.println("4.退出该系统");
System.out.println("请输入您的选项");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
switch(choice) {
case 1:Top(music);returnMenu1(file);
case 2:advance(music);returnMenu1(file);
case 3:add(file);returnMenu1(file);
case 4:esc();
}
}
public static void returnMenu1(File file) throws IOException {
Scanner inputScanner = new Scanner (System.in);
System.out.println("输入0可返回菜单");
if(inputScanner.nextInt()==0)
Menu(file);
else
System.out.println("已退出系统");
}
//置顶歌曲
public static void Top(LinkedList<String> music) {
System.out.println("歌单:"+music);
System.out.println("请输入你想要置顶的歌曲:");
Scanner in = new Scanner(System.in);
name = in.next();
music.addFirst(name);
music.removeLastOccurrence(name);
System.out.println("已置顶歌曲 :"+music);
System.out.println("歌单:"+music);
}
//歌曲提前一位
public static void advance(LinkedList<String> music) {
Scanner in=new Scanner(System.in);
System.out.print("请输入您想要前移的歌曲名称:");
String name=in.next();
int i = music.indexOf(name);//提前
if(i<0) {
System.out.println("当前列表没有这首歌");
}else if(i==0) {
System.out.println("当前歌曲"+name+"在最前面");
}else {
music.remove(name);
music.add(i-1, name);
}
System.out.println("已经前移歌曲 :"+name);
System.out.println("歌单:"+music);
}
public static void add(File file) throws IOException {
BufferedReader bufr = new BufferedReader(new FileReader(file));
BufferedWriter bufw = new BufferedWriter(new FileWriter(file,true));
//先是读取显示
String show;
System.out.println("这是你的歌单:");
while((show = bufr.readLine()) != null) {
System.out.println(show+",");
}
Scanner in = new Scanner(System.in);
String song = null;
System.out.println("请输入你想输入的歌曲:");
song = in.next();
bufw.write(song);
bufw.newLine();
System.out.println("["+song+"]"+"添加成功");
music.add(song);
//关闭流
bufr.close();
bufw.close();
}
}
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
试试能不能下次运行的时候LInkedList里面有文档里的数据