[英]how do I get data from a text file and save it into a string?
如何從文本文件中獲取數據並將其保存為字符串?
例如,我的文本文件的編號為1,4,5,6,8和10.4。 這些數字可以在同一行或單獨的行上。 我想將它們連接成一個字符串,如下所示: 1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
我的代碼無法正常工作。
您的代碼工作正常,問題是,你想兩個times.after首次訪問您的文件的內容while loop
中, hasnext()
方法將返回false.because你已經訪問的所有元素在第一while
循環。 所以它不會執行 -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
除此之外你的代碼還可以。 如果你想把它存儲在字符串中,那么在你的第一個while loop
進行小修改,如下所示 -
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
我想這會給你你想要的東西。
你好我認為下面的代碼對你有用,根據你的問題,我有txt文件的數據,首先我得到文件的位置然后我試圖獲取內容,最后我打印到控制台
File f = new File("D:\\temp.txt");
String content11 = FileUtils.readFileToString(f);
System.out.println(content11);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.