如何使用 Java 读取文件
How can I use Java to read a file
所以我有这段代码,我想在其中允许用户输入任意长度的字符串并加密代码。为了使它不仅仅是一个基本项目,我认为拥有一个 'save' 功能会很酷,用户可以在以后使用该功能。
问题就出现在这里。我正在浏览 Youtube 和一段视频,在那里我学习了如何创建文件和写入文件。当我转到读取文件(加载)的部分时,我看到我需要为文件中的每个字符创建一个变量。因为我不知道要创建多少个变量,所以我被卡住了。
在他的代码(我将展示它)中,他使用 while
循环遍历文件的内容,并使用变量打印出文件的内容。我的代码如下:
import java.util.*;
public class Sep {
private Formatter x;
public void openfile () {
try {
x = new Formatter("Gogo.txt");
}
catch (Exception e) {
System.out.println("You have an error mate!!");
}
}
public void addStuff() {
x.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
}
public void closeFile () {
x.close();
}
}
由于用户将输入他想要的任何内容,所以我不知道要创建多少个变量。
youtuber 有这个:
import java.util.*;
public class Sep {
private Formatter g;
private Scanner x;
public void openfile () {
try {
g = new Formatter("Gogo.txt");
x = new Scanner(new File("gogo.txt"));
}
catch (Exception e) {
System.out.println("You have an error mate!!");
}
}
public void addStuff() {
g.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
}
public void readFile() {
while(x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
public void closeFile () {
x.close();
}
}
您可以使用 ArrayList:
ArrayList<String> al = new ArrayList<String>();
al.add(x.next);//this is in while loop
然后打印出 ArrayList:
foreach(String s : al)
System.out.printf("%s\n", s);
所以我有这段代码,我想在其中允许用户输入任意长度的字符串并加密代码。为了使它不仅仅是一个基本项目,我认为拥有一个 'save' 功能会很酷,用户可以在以后使用该功能。
问题就出现在这里。我正在浏览 Youtube 和一段视频,在那里我学习了如何创建文件和写入文件。当我转到读取文件(加载)的部分时,我看到我需要为文件中的每个字符创建一个变量。因为我不知道要创建多少个变量,所以我被卡住了。
在他的代码(我将展示它)中,他使用 while
循环遍历文件的内容,并使用变量打印出文件的内容。我的代码如下:
import java.util.*;
public class Sep {
private Formatter x;
public void openfile () {
try {
x = new Formatter("Gogo.txt");
}
catch (Exception e) {
System.out.println("You have an error mate!!");
}
}
public void addStuff() {
x.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
}
public void closeFile () {
x.close();
}
}
由于用户将输入他想要的任何内容,所以我不知道要创建多少个变量。 youtuber 有这个:
import java.util.*;
public class Sep {
private Formatter g;
private Scanner x;
public void openfile () {
try {
g = new Formatter("Gogo.txt");
x = new Scanner(new File("gogo.txt"));
}
catch (Exception e) {
System.out.println("You have an error mate!!");
}
}
public void addStuff() {
g.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
}
public void readFile() {
while(x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
public void closeFile () {
x.close();
}
}
您可以使用 ArrayList:
ArrayList<String> al = new ArrayList<String>();
al.add(x.next);//this is in while loop
然后打印出 ArrayList:
foreach(String s : al)
System.out.printf("%s\n", s);