我正在将应用程序从Symbian/iPhone移植到Android,其中一部分是将一些数据保存到文件中.我使用FileOutputStream将文件保存到私有文件夹/ data/data/package_name/files中:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
Run Code Online (Sandbox Code Playgroud)
现在我正在寻找一种如何加载它们的方法.我正在使用FileInputStream,但它允许我逐字节读取文件,这是非常低效的:
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
String data = new String(fileContent);
Run Code Online (Sandbox Code Playgroud)
所以我的问题是如何使用更好的方式读取文件?
file-io android fileinputstream fileoutputstream android-file
我在“resource/json/templates”文件夹中有一些 Json 文件。我想读取这些 Json 文件。到目前为止,下面的代码片段允许我在 IDE 中运行程序时执行此操作,但在 jar 中运行程序时失败。
JSONParser parser = new JSONParser();
ClassLoader loader = getClass().getClassLoader();
URL url = loader.getResource(templateDirectory);
String path = url.getPath();
File[] files = new File(path).listFiles();
PipelineTemplateRepo pipelineTemplateRepo = new PipelineTemplateRepoImpl();
File templateFile;
JSONObject templateJson;
PipelineTemplateVo templateFromFile;
PipelineTemplateVo templateFromDB;
String templateName;
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
templateFile = files[i];
templateJson = (JSONObject) parser.parse(new FileReader(templateFile));
//Other logic
}
}
}
catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。
多谢。
我需要使用Java逐行读取文本文件.我使用available()
方法FileInputStream
检查并循环文件.但是在读取时,循环在最后一行之前的行之后终止.即,如果文件有10行,则循环只读取前9行.使用的片段:
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
Run Code Online (Sandbox Code Playgroud) 下面是我处理徽标打印的代码.徽标放在res/drawable文件夹中.当我运行应用程序时,它会抛出:
java.io.FileNotFoundException: /android.resource:/com.android.test/2130837505 (No such file or directory).
Run Code Online (Sandbox Code Playgroud)
有什么建议?
public boolean printLogo()
{
Uri logo_path = Uri.parse("android.resource://com.android.test/" + R.drawable._logo);
File logo = new File(logo_path.toString());
byte[] logo_bytes = new byte[(int) logo.length()];
System.out.print("Length:" + logo.length());
FileInputStream fs;
try {
fs = new FileInputStream(logo);
fs.read(logo_bytes);
fs.close();
mChatService.write(logo_bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return true;
}
Run Code Online (Sandbox Code Playgroud) 我对程序最近开始抛出的错误感到困惑.
java.io.IOException: No space left on device
at java.io.FileInputStream.close0(Native Method)
at java.io.FileInputStream.close(FileInputStream.java:259)
at java.io.FilterInputStream.close(FilterInputStream.java:155)
Run Code Online (Sandbox Code Playgroud)
我假设因为这是一个FileInputStream,该文件被保存在内存中,而不是物理磁盘上.内存级别看起来很棒,磁盘空间也是如此.这特别令人困惑,因为它发生在FileInputStream的结束时.感谢您对如何发生这种情况的任何解释.
编辑:审查代码
if (this.file.exists()) {
DataInputStream is = new DataInputStream(new FileInputStream(this.file));
this.startDate = new DateTime(is.readLong(), this.timeZone);
this.endDate = new DateTime(is.readLong(), this.timeZone);
is.close();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我只打开文件,阅读一些内容,然后关闭文件.
假设我有2个线程,一个是写入a FileOutputStream
,一个是从a读取FileInputStream
.
第一个线程写了x个字节.
什么时候字节被认为准备好读取?
该flush()
方法有一个空的实现FileOutputStream
,因此刷新不会做任何事情.
我的假设是,一旦我写入FileOutputStream
字节就准备好了.
现实生活中的例子FileOutputStream
,并FileInputStream
说会证明执行后out.write()
写入字节都没有准备好被消耗in.read()
将非常感激.相反的证据将更加受到重视.
我想在JSP中读取一个excel文件,为此我首先使用Web应用程序项目将文件上传到名为uploads的:D分区的文件夹中,我尝试用另一个java projet 读取excel上传文件.这两个代码都在工作.这是通过Web应用程序项目(JSP和SERVLET)在特定文件夹中上传的代码:
图书馆
的index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Upload File</title>
</head>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data">
Select File : <input type="file" name="filetoupload">
<br/>
<input type="submit" value="Upload File">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
UploadServlet.java(Servlet的)
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class UploadFile extends HttpServlet{
String saveFile="D:/upload/";
protected …
Run Code Online (Sandbox Code Playgroud) excel file-upload fileinputstream apache-poi apache-commons-fileupload
如果我将文件中的字节读入byte [],我发现当数组大约1 MB而不是128 KB时,FileInputStream的性能会更差.在我测试的2个工作站上,它几乎是128 KB的两倍.这是为什么?
import java.io.*;
public class ReadFileInChuncks
{
public static void main(String[] args) throws IOException
{
byte[] buffer1 = new byte[1024*128];
byte[] buffer2 = new byte[1024*1024];
String path = "some 1 gb big file";
readFileInChuncks(path, buffer1, false);
readFileInChuncks(path, buffer1, true);
readFileInChuncks(path, buffer2, true);
readFileInChuncks(path, buffer1, true);
readFileInChuncks(path, buffer2, true);
}
public static void readFileInChuncks(String path, byte[] buffer, boolean report) throws IOException
{
long t = System.currentTimeMillis();
InputStream is = new FileInputStream(path);
while ((readToArray(is, buffer)) != 0) {} …
Run Code Online (Sandbox Code Playgroud) 我以前从未接触过Java IO API的经验,现在我真的很沮丧.我发现很难相信它有多奇怪和复杂,做一个简单的任务有多难.
我的任务:我有2个位置(起始字节,结束字节),pos1
和pos2
.我需要读取这两个字节之间的行(包括起始字节,不包括结尾字节),并将它们用作UTF8字符串对象.
例如,在大多数脚本语言中,它将是一个非常简单的1-2-3-liner(在Ruby中,但它对于Python,Perl等基本相同):
f = File.open("file.txt").seek(pos1)
while f.pos < pos2 {
s = f.readline
# do something with "s" here
}
Run Code Online (Sandbox Code Playgroud)
使用Java IO API很快就会出现问题;)实际上,我看到了两种\n
从常规本地文件中读取行(以...结尾)的方法:
getFilePointer()
和seek(long pos)
,但它的readLine()读取非UTF8字符串(甚至不是字节数组),但非常奇怪的字符串具有破坏的编码,并且它没有缓冲(这可能意味着每个read*()
调用都将被转换为单个不连续的OS read()
= >相当慢).readLine()
方法,它甚至可以进行一些搜索skip(long n)
,但它无法确定已经读取的偶数字节数,也没有提到文件中的当前位置.我试过用类似的东西:
FileInputStream fis = new FileInputStream(fileName);
FileChannel fc = fis.getChannel();
BufferedReader br = new BufferedReader(
new InputStreamReader(
fis,
CHARSET_UTF8
)
);
Run Code Online (Sandbox Code Playgroud)
...然后使用fc.position()
获取当前文件读取位置并fc.position(newPosition)
设置一个,但它似乎在我的情况下不起作用:看起来它返回由BufferedReader完成的缓冲区预填充的位置,或类似的东西 - …
I'm trying to read from a file called "quiz_questions.txt" in my res/raw folder. The code I have compiles, but it looks like it stops before it gets to the FileInputStream. Maybe it is opening it, but not reading it. I'm not sure.
import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
public class Questions extends Activity {
public String[][] questions = new String[10][5];
public void fillArray() {
{
Context con = null;
try {
//fis = new BufferedInputStream(new FileInputStream("res/raw/quiz_questions.txt"));
FileInputStream fis …
Run Code Online (Sandbox Code Playgroud) fileinputstream ×10
java ×7
android ×3
file-io ×2
android-file ×1
apache-poi ×1
drawable ×1
excel ×1
exception ×1
file ×1
file-upload ×1
io ×1
ioexception ×1
jar ×1
nio ×1
performance ×1
uri ×1