[英]how do I get data from a text file and save it into a string?
How do I get data from a text file and save it into a string? 如何从文本文件中获取数据并将其保存为字符串?
For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. 例如,我的文本文件的编号为1,4,5,6,8和10.4。 These numbers can be on the same line or on separate lines.
这些数字可以在同一行或单独的行上。 I want to concatenate them into a string, like so:
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");
}
}
}
}
My code does not work correctly. 我的代码无法正常工作。
Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop
, the hasnext()
method will return false.because you already accessed all the element in first while
loop. 您的代码工作正常,问题是,你想两个times.after首次访问您的文件的内容
while loop
中, hasnext()
方法将返回false.because你已经访问的所有元素在第一while
循环。 so it will not execute - 所以它不会执行 -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
Other than that your code is fine. 除此之外你的代码还可以。 if you want store it in string also then do small modification in your first
while loop
as below- 如果你想把它存储在字符串中,那么在你的第一个
while loop
进行小修改,如下所示 -
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
I think this will give you what you want. 我想这会给你你想要的东西。
Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console 你好我认为下面的代码对你有用,根据你的问题,我有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.