如果我不保存,为什么我的文件会被清除?

发布于 2024-08-29 02:35:50 字数 1450 浏览 12 评论 0原文

我的程序应该在相册中维护照片集合。它首先读取照片文件夹并将它们添加到我的相册中。然后它会打印一个菜单,允许用户列出所有照片、添加照片、查找照片、保存和退出程序。现在,如果我运行我的程序,它会将 100 张照片添加到相册中,但如果我退出程序而不保存,它会清除我正在读取的文件,即使我没有添加照片或对相册做任何操作,并且我不知道为什么。

这是我打印到文件的方法:

private static void saveFile(PrintWriter writer) {
 String result;
  ArrayList<Photo> temp = album.getPhotoAlbum();
  for (int i = 0; i < temp.size(); i++){
   result = temp.get(i).toString() + "\n";
   writer.println(result);
  }
  writer.close();
 }

实例化 PrintWriter 的位置:

File file = new File(args[0] + File.separator + "album.dat");

try {
   PrintWriter fout =  
new PrintWriter(new FileWriter(file));
   fileWriter = fout;
  } catch (IOException e){
   System.out.println("ReadFromFile: Folder " + args[0]
                          + " is not found.");
   System.exit(0);
  }

以及在我的 runMenu 方法中调用它的位置:

private static void runMainMenu(Scanner scan) {
  String input;
  do {
   showMainMenu();
  input = scan.nextLine().toLowerCase();
  switch (input.charAt(0)) {
  case 'p':
   System.out.println(album.toString());
   break;
  case 'a': 
  album.addPhoto(readPhoto(scan, t));
   break;
  case 'f':
  findMenu(scan);
   break;
  case 's':
   saveFile(fileWriter);
   System.exit(0);
   break;
  case 'q':
   break;
  default:
   System.out.println("Invalid entry: " + 
     input.charAt(0));
   break;
  }
  } while (!input.equalsIgnoreCase("q"));
 }

My program is suppose to maintain a collection of Photos in a PhotoAlbum. It begins by reading a folder of photos and adds them to my PhotoAlbum. It then prints a menu that allows the user to list all the photos, add a photo, find a photo, save, and quit the program. Right now if I run my program it will add the 100 photos to the PhotoAlbum, but if I quit the program without saving, it clears the file I am reading from even if I haven't added a photo or done anything to the PhotoAlbum and I'm not sure why.

Here is my method for printing to a file:

private static void saveFile(PrintWriter writer) {
 String result;
  ArrayList<Photo> temp = album.getPhotoAlbum();
  for (int i = 0; i < temp.size(); i++){
   result = temp.get(i).toString() + "\n";
   writer.println(result);
  }
  writer.close();
 }

And where the PrintWriter is instantiated:

File file = new File(args[0] + File.separator + "album.dat");

try {
   PrintWriter fout =  
new PrintWriter(new FileWriter(file));
   fileWriter = fout;
  } catch (IOException e){
   System.out.println("ReadFromFile: Folder " + args[0]
                          + " is not found.");
   System.exit(0);
  }

And where it is called in my runMenu Method:

private static void runMainMenu(Scanner scan) {
  String input;
  do {
   showMainMenu();
  input = scan.nextLine().toLowerCase();
  switch (input.charAt(0)) {
  case 'p':
   System.out.println(album.toString());
   break;
  case 'a': 
  album.addPhoto(readPhoto(scan, t));
   break;
  case 'f':
  findMenu(scan);
   break;
  case 's':
   saveFile(fileWriter);
   System.exit(0);
   break;
  case 'q':
   break;
  default:
   System.out.println("Invalid entry: " + 
     input.charAt(0));
   break;
  }
  } while (!input.equalsIgnoreCase("q"));
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半枫 2024-09-05 02:35:50

您可能在打开流后没有关闭它。如果它已经被打开,那么在任何情况下(不仅仅是当你实际修改它时)你都应该这样做。

这就是为什么finally块在java中很有用,看看此处了解有关使用 java 流的良好实践。

Probably you are not closing the stream after having opened it. You should do it in any case (not just when you actually modify it) if it has been opened..

That's why finally blocks are useful in java, take a look here for good practices about using java streams..

Oo萌小芽oO 2024-09-05 02:35:50

当您通过将 File 对象传递到 PrintWriter 来打开文件时,您实际上是在让 PrintWriter 控制文件的打开方式(很可能是创建),从而删除现有文件并为新文件做好准备一个写。

因为您从不保存(关闭流),所以 PrintWriter 中缓冲的任何数据都不会输出到文件中。

您需要重构您的文件方法,如果您使用 File.Open(...) 函数,您可以指定追加会话。

FileStream outStream = File.Open(myFileName, FileMode.Append);
PrintWriter pw = new PrintWriter(outStream);

这样,您的文件不会仅通过打开而被清除,并且您可以附加到末尾。

或者,您可以在需要时通过使用 FileMode.Create 打开文件来强制清除文件

。你应该了解 using 块,它非常有用。

When you open the file by passing a File object into the Print Writer you're essentially letting the PrintWriter govern how the file is opened (most likely Create) which deletes the existing file and readies a new one for a write.

Because you never save (close the stream), any data buffered in the PrintWriter isn't outputted to the file.

You need to refactor your file approach, if you use the File.Open(...) function you can specify an append session.

FileStream outStream = File.Open(myFileName, FileMode.Append);
PrintWriter pw = new PrintWriter(outStream);

This way your file wont be cleared just by opening to it, and you may append to the end.

Alternatively you can force the file to be cleared when you want it to be by opening it with FileMode.Create

P.S. you should learn about the using block, it's very usefull.

比忠 2024-09-05 02:35:50

确保您正在关闭流。
另请检查您是否没有覆盖原始文件。
Aren B 给出了一些 C# 代码,但等效的 Java 代码是:

PrintWriter printWriter = new PrintWriter( new FileWriter("path/to/album.dat", true));

Make sure that you are closing your streams.
Also check that you are not overwriting the original file.
Aren B gave some C# code, but the Java equivalent would be:

PrintWriter printWriter = new PrintWriter( new FileWriter("path/to/album.dat", true));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文