This question already has answers here:
How do I load a resource and use its contents as a string in Spring
(7 answers)
Closed 9 months ago.
I have a text file with path as resources/templates/temp.txt. I tried reading it with built in Files.readAllBytes() function found in java.nio but that results in an NullPointerException. My code looks as follows:
try {
File file = new File(getClass().getResource("templates/temp.txt").getFile());
String temp = new String(Files.readAllBytes(Paths.get(file.getPath())));
System.out.println(temp);
}catch(Exception e){
e.printStackTrace();
}
The file actually does exist at this location because I am able to get an InputStream and use that in an InputStreamReader and BufferedReader to read the file line-by-line.
InputStream input = this.getClass().getClassLoader().getResourceAsStream(path)
//path here is "templates/temp.txt"
I would like to read this file with a built in method rather than iterating over the entire thing.
Would appreciate it very much if someone can help with this. Thanks in advance!
How does your code even compile? You have static reference in non-static env:
... new File(getClass().getResource ...
try to get the bytearray before transforming into string:
try {
byte[] tmpba = Files.readAllBytes(Paths.get("templates/temp.txt"));
String s = new String(tmpba);
System.out.println(s);
}catch(Exception e){
e.printStackTrace();
}
Related
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 4 years ago.
I open file as follows
private static Formatter x;
public static void openFile(){
try{
x=new Formatter("sarit.text");
}
catch(Exception e){
System.out.println("error");
}
}
Here I add a information to the file but the problem of adding the information to this file erases everything that was in the file before inserting the information
public static void addRecords(String age,String city,String name, String password){
x.format(" "+name+" "+password+" "+age+" "+city+"\n");
}
public static void closeFile(){
x.close();
}
Welcome to StackOverflow!
You are doing new Formatter("sarit.text");
Checking javadoc for
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)
if the file exists then it will be truncated to zero size
you need to append to file.
Question How to append text to an existing file in Java provides answers how to append to file in java.
Assuming you're using java.util.Formatter, the documentation specifically says:
If the file exists then it will be truncated to zero size; otherwise,
a new file will be created
You have to find a different way to do it, with a BufferedWriter for example:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
The true parameter tells the FileWriter to append to the file.
If you want to use formatting, use String.format():
writer.write(String.format(...));
This question already has answers here:
File to byte[] in Java
(27 answers)
Closed 6 years ago.
So, I have this .mp4 video file which I would like to convert into bytes and send it to my client.
At client, I'll receive all the bytes over RTP and then construct my own .mp4 file.
Please help me doing this, I'm not posting any code because, I don't know where to start and I'm all new to file handling in java
Thanks
You can use the Apache commons IOUtils.toByteArray method to create a byte array from an InputStream
Example:
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
class ConvertToByteArray
{
public static void main(String args[])
{
FileInputStream is = null;
try
{
is = new FileInputStream("file.mp4");
byte [] byteArr = IOUtils.toByteArray(is);
}
catch (IOException ioe)
{}
finally
{
// close things
}
}
}
You can download the jar her at Apache Commons IO
This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 7 years ago.
I am using Yahoo's URL request ability to download stock data. I have found a java application that downloads the data every 5 seconds. I cant figure out how one would go about downloading stock data to a certain folder in ones computer while using the basic code I have used in the application. There has been other posts about how to save yahoo URL request data to a certain location but it does not use the same code format that I'm using. All ideas, source code, and links explaining how I should do this would be very helpful. Thank you for your help!
My code:
import java.awt.Desktop;
import java.net.URL;
public class Downloader {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread.sleep(5000);
try {
Desktop.getDesktop()
.browse(new URL(
"http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab")
.toURI());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
you could use Java's IO capabilities, Are you trying to write a GUI, if not any specific reason to use AWT's Desktop class?
Try this sample code:
URL yahooFinance = new URL("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab");
ReadableByteChannel channel = Channels.newChannel(yahooFinance.openStream());
FileOutputStream fos = new FileOutputStream("quotes.csv");
fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
You can also use org.apache.commons.io.FileUtils
java.net.URL yahooFinance = new java.net.URL("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab");
File f = new File("quotes.csv");
FileUtils.copyURLToFile(yahooFinance, f);
This question already has answers here:
Java Properties: How to keep non key=value lines?
(2 answers)
Adding comments in a properties file line by line
(3 answers)
Closed 7 years ago.
I have a .properties file which have number of comments in it, when I try to update the content of the file other than the comments, even though my comments are disappearing, how to retain my comments?
Here is the config.properties file:
#name of user
name=user1
#id of user
id=id1
and the code to update the properties file, I used
public class SetLog {
public static void setPath()
{
File file = new File("./config.properties");
Properties prop = new Properties();
FileInputStream objInput = null;
try {
objInput = new FileInputStream(file);
prop.load(objInput);
objInput.close();
FileOutputStream out = new FileOutputStream("./config.properties");
//update the content
prop.setProperty("name", "user2");
prop.store(out, null);
out.close();
} catch (Exception e) {}
}
}
After I run the above code, properties file content changed to:
name=user2
id=id1
But I want in this format:
#name of user
name=user2
#id of user
id=id1
How to retain my comments, please help!
This has been answered in a similar question: Adding comments in a Property File. Basically it boils down to using the Apache Commons extension to read and write Property Files.
Try to read the characters in the file and ignore those lines beginning with # .
See this link
I need to write something into a text file's beginning. I have a text file with content and i want write something before this content. Say i have;
Good afternoon sir,how are you today?
I'm fine,how are you?
Thanks for asking,I'm great
After modifying,I want it to be like this:
Page 1-Scene 59
25.05.2011
Good afternoon sir,how are you today?
I'm fine,how are you?
Thanks for asking,I'm great
Just made up the content :) How can i modify a text file like this way?
You can't really modify it that way - file systems don't generally let you insert data in arbitrary locations - but you can:
Create a new file
Write the prefix to it
Copy the data from the old file to the new file
Move the old file to a backup location
Move the new file to the old file's location
Optionally delete the old backup file
Just in case it will be useful for someone here is full source code of method to prepend lines to a file using Apache Commons IO library. The code does not read whole file into memory, so will work on files of any size.
public static void prependPrefix(File input, String prefix) throws IOException {
LineIterator li = FileUtils.lineIterator(input);
File tempFile = File.createTempFile("prependPrefix", ".tmp");
BufferedWriter w = new BufferedWriter(new FileWriter(tempFile));
try {
w.write(prefix);
while (li.hasNext()) {
w.write(li.next());
w.write("\n");
}
} finally {
IOUtils.closeQuietly(w);
LineIterator.closeQuietly(li);
}
FileUtils.deleteQuietly(input);
FileUtils.moveFile(tempFile, input);
}
I think what you want is random access. Check out the related java tutorial. However, I don't believe you can just insert data at an arbitrary point in the file; If I recall correctly, you'd only overwrite the data. If you wanted to insert, you'd have to have your code
copy a block,
overwrite with your new stuff,
copy the next block,
overwrite with the previously copied block,
return to 3 until no more blocks
As #atk suggested, java.nio.channels.SeekableByteChannel is a good interface. But it is available from 1.7 only.
Update : If you have no issue using FileUtils then use
String fileString = FileUtils.readFileToString(file);
This isn't a direct answer to the question, but often files are accessed via InputStreams. If this is your use case, then you can chain input streams via SequenceInputStream to achieve the same result. E.g.
InputStream inputStream = new SequenceInputStream(new ByteArrayInputStream("my line\n".getBytes()), new FileInputStream(new File("myfile.txt")));
I will leave it here just in case anyone need
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (FileInputStream fileInputStream1 = new FileInputStream(fileName1);
FileInputStream fileInputStream2 = new FileInputStream(fileName2)) {
while (fileInputStream2.available() > 0) {
byteArrayOutputStream.write(fileInputStream2.read());
}
while (fileInputStream1.available() > 0) {
byteArrayOutputStream.write(fileInputStream1.read());
}
}
try (FileOutputStream fileOutputStream = new FileOutputStream(fileName1)) {
byteArrayOutputStream.writeTo(fileOutputStream);
}