我需要从.txt文件中读取f_name,l_name,username,密码并将这些信息保存在不同的字符串中。
以下是我逐行读取的代码:
<html>
<head>
<title>My first styled page</title>
</head>
<body>
<script>
var reader = new FileReader();
reader.onload = function(){
var text = reader.result;
document.querySelector('body').append(text);
};
reader.readAsText(README, "us-ascii");
</script>
<!-- Site navigation menu -->
<ul class="navbar">
<li><a href="alamode-fetch">Alamode</a>
<li><a href="README">Readme</a>
<li><a href="town.html">My town</a>
<li><a href="links.html">Links</a>
</ul>
<!-- Main content -->
<h1>My first styled page</h1>
<p>Welcome to my styled page!
<p>It lacks images, but at least it has style.And it has links, even if they don't go anywhere…
<p>There should be more here, but I don't know what yet.
<!-- Sign and date the page, it's only polite! -->
<address>Made 5 April 2004<br>
by myself.
</address>
</body>
</html>
但我不知道如何将每个名字保存在变量f_name中,变量l_name中的每个姓氏,... 这个f_name,l_name,username,password中的每一个都在文件的新行中。
包含数据的文件示例:
import java.io.*;
public class Users {
public static void main(String[] args) {
try {
File file = new File("users.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
此f_name,l_name,username,password中的每一个都在文件的新行中。
您可以像这样一次读取四行
String f_name = bufferedReader.readLine();
String l_name = bufferedReader.readLine();
String username = bufferedReader.readLine();
String password = bufferedReader.readLine();
答案 1 :(得分:0)
试试这个:
添加以下行:
private BufferedReader innerReader;
并使用此方法:
private List<String> loadFile(Reader reader)
throws IllegalArgumentException, IOException{
List<String> fileList = new ArrayList<String>();
if(reader == null)
{
throw new IllegalArgumentException("Reader non valido");
}
String line;
innerReader = new BufferedReader(reader);
try
{
while((line = innerReader.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line Empty");
fileList.add(line);
}
} catch (IOException e) {
throw new IOException(e);
}
return fileList;
}
然后在主要:
MyClass myClass = new MyClass();
List<String> myList = new ArrayList<String>();
try {
myList = myClass.loadFile(new FileReader("YourFile.txt"));
} catch (IllegalArgumentException | IOException e) {
e.printStackTrace();
}
for(String s : myList)
{
System.out.println(s);
}
try {
myClass.innerReader.close();
} catch (IOException e) {
e.printStackTrace();
}
输出:
约翰
约翰逊
约翰尼拉
1234
大卫
戴维森
戴维
1234