Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a file dictionary.txt and I need to get that file from the raw folder so I googled around and found this:
Here's an example:
"android.resource:///"+getPackageName()+ "/" + R.raw.dictionary;
but it did not work, Any idea?
Edit:
here is what i am doing
for(String line: FileUtils.readLines(file))
{
if(line.toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
You can get an input stream on a raw resource by using:
getResources().openRawResource(R.raw.dictionary);
EDIT:
From your edit, there really isn't a reason as to why you would specifically need the file rather than just using the input stream available from the openRawResource(int id) method...just use an existing java class http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.InputStream,%20java.lang.String%29.
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.dictionary));
while(scanner.hasNextLine()){
{
if(scanner.nextLine().toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
}
Unfortunately you can not create a File object directly from the raw folder. You need to copy it in your sdcard or inside the application`s cache.
you can retrieve the InputStream for your file this way
InputStream in = getResources().openRawResource(R.raw.yourfile);
try {
int count = 0;
byte[] bytes = new byte[32768];
StringBuilder builder = new StringBuilder();
while ( (count = is.read(bytes,0 32768) > 0) {
builder.append(new String(bytes, 0, count);
}
is.close();
reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
} catch (IOException e) {
e.printStackTrace();
}
EDIT:
to copy it over to internal storage:
File file = new File(this.getFilesDir() + File.separator + "fileName.ext");
try {
InputStream inputStream = resources.openRawResource(R.id._your_id);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileOutputStream.write(buf,0,len);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e1) {}
Now you have a File that you can access anywhere you need it.
Place the file in the assets folder and open it like this
getResources().getAssets().open("dictionary.txt");
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.
This is what I have tried:
JMenuItem mntmOpen = new JMenuItem("Open");
mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmOpen) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
Path HI = file.toPath();
try( Stream<String> lines = Files.lines(HI)
){
for( String line : (Iterable<String>) lines::iterator )
{
editorPane.setText(line);
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am quite new to coding in Java and I am trying to make a plugin which creates a character template. The user will type the command /char name . I want it to then check if the command sender's file exists and if so it will write under the field "Name: " in their .dat file. If the file does not exist then it will create a file and write in that field. The only problem I am having is creating and writing and reading from the file. At one point I managed to get it to create the user file and write the name that they set but I couldn't write more as it would write something stupid like "Name: Gender" in the file. I also have no idea how to read from the file as well as it needs to be able to get their set name to change the name tag above their head.
This is an example of the code I am using on the command "/char gender":
if (label.equalsIgnoreCase("char gender")) {
if (args.length < 2) {
sender.sendMessage("/char gender <Male or Female>");
return false;
}
if (args.equals("male")) {
PrintWriter writer1;
try {
writer1 = new PrintWriter("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml", "UTF-8");
writer1.println("Gender: Male");
writer1.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
File file = new File("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml");
}
}
else if (args.equals("female")) {
PrintWriter writer1;
try {
writer1 = new PrintWriter("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml", "UTF-8");
writer1.println("Gender: Female");
writer1.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
File file = new File("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml");
}
}
else {
sender.sendMessage("/char gender <male or female>");
}
I am using a .yml file to test if it works because some reason, it will not create the player.dat
You are using the args array incorrectly:
if (args.equals("male"))
else if (args.equals("female"))
A String[] can never be a String so those will always both fail. Assuming the args translates as follows:
"/char gender male" -> new String[]{"/char", "gender", "male"}
You will need to use:
if (args[2].equals("male"))
else if (args[2].equals("female"))
Additionally, your error check should then be:
if (args.length <= 2)
As you'd need 3 arguments to specify it correctly.
The label can not have a space in it therefore:
if (label.equalsIgnoreCase("char gender"))
doesn't work
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to read huge pdf file using byte Array,
Here is my code for it.
String RESULT "D/new/certficateVisualFinal.pdf";
try {
FileInputStream fileInputStream=null;
File file = new File(RESULT);
byte[] bFile = new byte[(int) file.length()];
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
reader = new PdfReader(bFile);
pdfStamper = new PdfStamper(reader, new FileOutputStream(outPut));
pdfStamper.setOutlines(outlineVisual);
pdfStamper.setFormFlattening(true);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
But I got a OutOfMemoryErro when trying to
fileInputStream.read(bFile);
This is the Error
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:220)
please help me.Thank you.
Don't use the byte array at all. PdfReader has a constructor with an InputStream parameter, so you can just pass your FileInputStream directly to that.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to combine the song's in the format of mp4, mp3, Avi and wmv etc into one single file with help of Java code as in my server I have only JDK environment , so far I am using core Java file operation code. as follows.
String str="E:\\Movies\\Dark Skies (2013)\\Dark.mp4";
String ftr="F:\\CRS\\stv.mp4";
File file=new File(str);
File Kile=new File(ftr);
FileInputStream fis=new FileInputStream(file);
FileOutputStream fos=new FileOutputStream(Kile);
int luffersize=102400000;
byte[] luffer=new byte[luffersize];
int lenght=(int) fis.available();
if ((fis.read(luffer)) != 0) {
try {
fos.write(luffer, 0, lenght);
System.out.println("working");
} catch (IOException e) {
e.printStackTrace();
}finally{
fis.close();
fos.close();
}
}
}
Below is some code I whipped up to demonstrate how to concatenate (sequentially combine) two files together.
This doesn't take into account the MP4 file format. I'm not familiar with MP4, but MP3 is simply a series of 512-byte chunks with an arbitrary ID3 header. If you can strip off the header on the second file, general concatenation (i.e. "cat song1.mp song2.mp3 > newsong.mp3") of two music files does work reliably. But I'm not familiar with MP4 and I'm pretty sure it can support a variety of codecs. Hence, YMMV with this solution. Otherwise, do formal parsing and streaming with a codec library.
In any case, here's some sample code that will combine two files together:
public void CombineFiles(String filename1, String filename2, String filenameOuput) throws IOException
{
FileInputStream stream1 = new FileInputStream(filename1);
FileInputStream stream2 = new FileInputStream(filename2);
FileOutputStream streamOut = new FileOutputStream(filenameOuput);
FileInputStream stream = stream1;
byte [] buffer = new byte[8192]; // 8K temp buffer should suffice
while (true)
{
int bytesread = stream.read(buffer);
if (bytesread != -1)
{
streamOut.write(buffer, 0, bytesread);
}
else
{
// handle end of file and moving to the next file
if (stream == stream2)
break;
else
stream = stream2;
}
}
streamOut.close();
stream1.close();
stream2.close();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!
I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.
I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}