可能重复:
How to create a Java String from the contents of a file
我正在创建一个java程序来读取文件并创建文件以获得乐趣。我想知道如何从文件中读取并将其设置为字符串变量。或者将扫描仪变量转换为字符串变量,并将编码的一部分作为示例:
private Scanner x;
private JLabel label;
private String str;
public void openfile(String st){
try{
x = new Scanner(new File(st));
}
catch(Exception e){
System.out.println("Error: File Not Found");
}
}
答案 0 :(得分:1)
这是一个强大的oneliner。
String contents = new Scanner(file).useDelimiter("\\Z").next();
答案 1 :(得分:1)
很好的方法是使用Apache commons IOUtils将inputStream复制到StringWriter ......类似
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
或者,如果您不想混合Streams和Writers,可以使用ByteArrayOutputStream
答案 2 :(得分:0)
或者你甚至可以试试这个:
ArrayList <String> theWord = new ArrayList <String>();
//while it has next ..
while(x.hasNext()){
//Initialise str with word read
String str=x.next();
//add to ArrayList
theWord.add(str);
}
//print the ArrayList
System.out.println(theWord);
}
答案 3 :(得分:0)
以下是如何将文件读入字符串的示例:
public String readDocument(File document)
throws SystemException {
InputStream is = null;
try {
is = new FileInputStream(document);
long length = document.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new SystemException("Could not completely read file: " + document.getName());
}
return new String(bytes);
} catch (FileNotFoundException e) {
LOGGER.error("File not found exception occurred", e);
throw new SystemException("File not found exception occurred.", e);
} catch (IOException e) {
LOGGER.error("IO exception occurred while reading file.", e);
throw new SystemException("IO exception occurred while reading file.", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOGGER.error("IO exception occurred while closing stream.", e);
}
}
}
}
答案 4 :(得分:0)
BufferedReader in =new BufferedReader(new FileReader(filename));
String strLine;
while((strLine=in.readLine())!=null){
//do whatever you want with that string here
}