- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个简单的程序,使用不同的算法对输入文件中的整数进行排序。我还使用 filewriter 将结果输出到另一个文件。不幸的是,无论我如何更改代码,文件都会被覆盖。有什么建议吗?
一直在谷歌上寻找答案,并尝试改变我输入语法的方式,但没有任何效果。
重要部分:
设置编写器
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
输出到文件
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
它工作得很好,但是它用在 do while 循环中,带有嵌套的 if 语句,并且每个语句都会覆盖另一个语句。
其余代码以防需要 - 已更新 - 仍然无法正常工作
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
文件不断被覆盖,我如何阻止它并使其添加到文件中?
最佳答案
您不需要第一个FileWriter fileWriter = new FileWriter("Sorted output.txt");
;这实际上是创建/覆盖文件,之后您的 PrintWriter 再次打开它进行追加。
所以,改变一下
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
至
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
关于java - 将 boolean 值设置为 true,但 filewriter 仍然覆盖文件,有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927937/
今天我在一个 Java 应用程序中看到了几种不同的加载文件的方法。 文件:/ 文件:// 文件:/// 这三个 URL 开头有什么区别?使用它们的首选方式是什么? 非常感谢 斯特凡 最佳答案 file
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我有一个 javascript 文件,并且在该方法中有一个“测试”方法,我喜欢调用 C# 函数。 c# 函数与 javascript 文件不在同一文件中。 它位于 .cs 文件中。那么我该如何管理 j
需要检查我使用的文件/目录的权限 //filePath = path of file/directory access denied by user ( in windows ) File fil
我在一个目录中有很多 java 文件,我想在我的 Intellij 项目中使用它。但是我不想每次开始一个新项目时都将 java 文件复制到我的项目中。 我知道我可以在 Visual Studio 和
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a software
我有 3 个组件的 Twig 文件: 文件 1: {# content-here #} 文件 2: {{ title-here }} {# content-here #}
我得到了 mod_ldap.c 和 mod_authnz_ldap.c 文件。我需要使用 Linux 命令的 mod_ldap.so 和 mod_authnz_ldap.so 文件。 最佳答案 从 c
我想使用PIE在我的项目中使用 IE7。 但是我不明白的是,我只能在网络服务器上使用 .htc 文件吗? 我可以在没有网络服务器的情况下通过浏览器加载的本地页面中使用它吗? 我在 PIE 的文档中看到
我在 CI 管道中考虑这一点,我应该首先构建和测试我的应用程序,结果应该是一个 docker 镜像。 我想知道使用构建环境在构建服务器上构建然后运行测试是否更常见。也许为此使用构建脚本。最后只需将 j
using namespace std; struct WebSites { string siteName; int rank; string getSiteName() {
我是 Linux 新手,目前正在尝试使用 ginkgo USB-CAN 接口(interface) 的 API 编程功能。为了使用 C++ 对 API 进行编程,他们提供了库文件,其中包含三个带有 .
我刚学C语言,在实现一个程序时遇到了问题将 test.txt 文件作为程序的输入。 test.txt 文件的内容是: 1 30 30 40 50 60 2 40 30 50 60 60 3 30 20
如何连接两个tcpdump文件,使一个流量在文件中出现一个接一个?具体来说,我想“乘以”一个 tcpdump 文件,这样所有的 session 将一个接一个地按顺序重复几次。 最佳答案 mergeca
我有一个名为 input.MP4 的文件,它已损坏。它来自闭路电视摄像机。我什么都试过了,ffmpeg , VLC 转换,没有运气。但是,我使用了 mediainfo和 exiftool并提取以下信息
我想做什么? 我想提取 ISO 文件并编辑其中的文件,然后将其重新打包回 ISO 文件。 (正如你已经读过的) 我为什么要这样做? 我想开始修改 PSP ISO,为此我必须使用游戏资源、 Assets
给定一个 gzip 文件 Z,如果我将其解压缩为 Z',有什么办法可以重新压缩它以恢复完全相同的 gzip 文件 Z?在粗略阅读了 DEFLATE 格式后,我猜不会,因为任何给定的文件都可能在 DEF
我必须从数据库向我的邮件 ID 发送一封带有附件的邮件。 EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Adventure Works Admin
我有一个大的 M4B 文件和一个 CUE 文件。我想将其拆分为多个 M4B 文件,或将其拆分为多个 MP3 文件(以前首选)。 我想在命令行中执行此操作(OS X,但如果需要可以使用 Linux),而
快速提问。我有一个没有实现文件的类的项目。 然后在 AppDelegate 我有: #import "AppDelegate.h" #import "SomeClass.h" @interface A
我是一名优秀的程序员,十分优秀!