How to avoid saving a file on hard drive? - java

Each time I run the following code, the file is saved on a hard drive. However, I want it to be saved only in the Object Storage container.
OSClient os = OSFactory.builder()
.endpoint("...")
.credentials("...","...")
.tenantName("...")
.authenticate();
String containerName = "MyImgs";
String objectName = "test.jpg";
BufferedWriter output = null;
try {
File f = new File(objectName);
output = new BufferedWriter(new FileWriter(f));
output.write(text);
String etag = os.objectStorage().objects().put(containerName,
objectName,
Payloads.create(f));
} catch ( IOException e ) {
e.printStackTrace();
}
UPDATE:
I am using this API.

Looking at the Javadoc for Payloads it has a method which takes in InputStream. To read an String as an InputStream you can do
Payloads.create(new ByteArrayInputStream(text.getBytes());
This will avoid the need to create a file just so you have something to read.

From reading the OpenStack4j API it is possible to create a payload from an InputStream, so why don't you do that instead of from a File?
Convert the text to an InputStream with a helper function like this:
private static InputStream newInputStreamFrom(String text) {
try {
return new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(); // should not occur
}
}
And then your code could look something like this:
OSClient os = OSFactory.builder()
.endpoint("...")
.credentials("...","...")
.tenantName("...")
.authenticate();
String containerName = "MyImgs";
String objectName = "test.jpg";
InputStream stream = newInputStreamFrom(text);
String etag = os.objectStorage().objects().put(containerName,
objectName,
Payloads.create(stream));

Related

How to load a tsv file for MALLET using FileInputStream in Java?

I want to load the flat text file passed in as 'TMFlatFile' (which is the .tsv file format to use in MALLET) into into the fileReader variable.
I have created the method, RunTopicModelling() and am having a problem with the try/except block.
I have created my File and FileInputStream objects, but dont know how to load it correctly into fileReader?
I have an error that "The method read(CharBuffer) in the type InputStreamReader is not applicable for the arguments (int)".
public class TopicModelling {
private void StartTopicModellingProcess(String filePath) {
JSONIOHelper jsonIO = new JSONIOHelper();
jsonIO.LoadJSON(filePath);
ConcurrentHashMap<String, String> lemmas = jsonIO.GetDocumentsFromJSONStructure();
SaveLemmaDataToFile("topicdata.txt" ,lemmas);
}
private void SaveLemmaDataToFile(String TMFlatFile, ConcurrentHashMap<String, String> lemmas) {
for (Entry<String, String> entry : lemmas.entrySet()) {
try (FileWriter writer = new FileWriter(TMFlatFile)) {
;
writer.write(entry.getKey() + "\ten\t" + entry.getValue() + "\r\n");
} catch (Exception e)
{
System.out.println("Saving to flat text file failed...");
}
}
}
private void RunTopicModelling(String TMFlatFile, int numTopics, int numThreads, int numIterations) {
ArrayList<Pipe> pipeList = new ArrayList <Pipe>();
// Pipes: tokenise, map to features
pipeList.add(new CharSequence2TokenSequence (Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));
pipeList.add(new TokenSequence2FeatureSequence());
InstanceList instances = new InstanceList (new SerialPipes(pipeList));
InputStreamReader fileReader = null;
//loads the file passed in via the TMFlatFile variable into the fileReader variable - this block I have a problem with
try {
File inFile = new File(TMFlatFile);
FileInputStream fis = new FileInputStream(inFile);
int line;
while ((line = fis.read()) != -1) {
}
fileReader.read(line);
}
fis.close();
}catch(
Exception e)
{
System.out.println("File Load Failed");
System.exit(1);
}
\\ // linking data to the pipeline
instances.addThruPipe(new CsvIterator(fileReader,Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),3,2,1));
}
Can someone tell me what is the correct way to do this?
It's hard to say what the immediate issue is because the code sample provided looks like it's missing important parts, and would not compile as written (for example Exception e) and regex without quotes).
The data import developers guide https://mimno.github.io/Mallet/import-devel has sample code that should be a good starting point.

read and write from Internal storage

I am having this exception when trying to read from the file
java.io.FileNotFoundException: /data/data/.../files
I used this method because it can handle Unicode text while reading from the file
public void save(String string )
{
String filename = "main";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String read()
{
try
{
Reader readerUnicode =
new InputStreamReader(new FileInputStream(getFilesDir()), Charset.forName("UTF-16"));
int e = 0;
String f="";
while ((e = readerUnicode.read()) != -1) {
// cast to char. The casting removes the left most bit.
f = f+Character.toString((char) e);
System.out.print(f);
}
return f;
}
catch(Exception e)
{
return e+"";
}
}
how can I retrieve the internal save path
thanks
You are using getFilesDir() But not setting the actual file name. Just the directory path.
Try adding the file name in. Plus, you should probably add an extension like .txt to both the save and load path.
new InputStreamReader(new FileInputStream(getFilesDir() + "/" + filename ), Charset.forName("UTF-16"));
and change filename to something more sensible.
String filename = "main.txt";
You could/should also check the file exists before accessing it. (Although you do try catch anyway)
File file = new File(getFilesDir() + "/" + filename);
if(!file.exists())
return "";

How to save a file to a directory

What I have so far:
A block of code that intakes a username and password and write it to a textfile.
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
try {
FileWriter userInfoWriter = new FileWriter(usernameFilename);
BufferedWriter writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.write("\r\n" + writePassword);
writeToFile.close();
What I need to accomplish:
Create a directory to a pre-made folder called users.
Save the file to usernameFilename to a directory.
What I've tried:
I've searched online everywhere! I cant find anything to do this :c
Extra info:
Since all computers are different, I would like to use the .getAbsolutePath() method when creating the directory.
Take a look at:
java.io.File
File#exists
File#isDirectory
File#mkDirs
You could update your code to look more look this...
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
File users = new File("users");
if ((users.exists() && users.isDirectory()) || users.mkdirs()) {
FileWriter userInfoWriter = null;
BufferedWriter writeToFile = null;
try {
userInfoWriter = new FileWriter(users.getPath() + File.seperator + usernameFilename);
writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.newLine();
writeToFile.write(writePassword);
//....
} finally {
try {
writeToFile.close();
} catch (Exception exp) {
}
}
} else {
throw new IOException("Could not create/find Users directory");
}

How to convert a String into a File Object in java?

I have file contents in a java string variable, which I want to convert it into a File object is that possible?
public void setCfgfile(File cfgfile)
{
this.cfgfile = cfgfile
}
public void setCfgfile(String cfgfile)
{
println "ok overloaded function"
this.cfgfile = new File(getStreamFromString(cfgfile))
}
private def getStreamFromString(String str)
{
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes())
is
}
As this is Groovy, you can simplify the other two answers with:
File writeToFile( String filename, String content ) {
new File( filename ).with { f ->
f.withWriter( 'UTF-8' ) { w ->
w.write( content )
}
f
}
}
Which will return a file handle to the file it just wrote content into
Try using the apache commons io lib
org.apache.commons.io.FileUtils.writeStringToFile(File file, String data)
You can always create a File object from a String using the File(String) constructor. Note that the File object represents only an abstract path name; not a file on disk.
If you are trying to create an actual file on disk that contains the text held by the string there are several classes that you can use, for example:
try {
Writer f = new FileWriter(nameOfFile);
f.write(stringToWrite);
f.close();
} catch (IOException e) {
// unable to write file, maybe the disk is full?
// you should log the exception but printStackTrace is better than nothing
e.printStackTrace();
}
FileWriter will use the platform default encoding when converting the characters of the string to bytes that can be written on disk. If this is a problem you can use a different encoding by wrapping FileOutputStream inside an OutputStreamWriter. For example:
String encoding = "UTF-8";
Writer f = new OutputStreamWriter(new FileOutputStream(nameOfFile), encoding);
To write a String to a file, you usually should use a BufferedWriter:
private writeToFile(String content) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(this.cfgfile));
bw.write(content);
}
catch(IOException e) {
// Handle the exception
}
finally {
if(bw != null) {
bw.close();
}
}
}
Besides, the new File(filename) simply instanciates a new File object with the name filename (it does not actually create the file on your disk). Therefore, you statement:
this.cfgfile = new File(getStreamFromString(cfgfile))
will simple instanciate a new File with the name the String returned by the this.cfgfile = new File(getStreamFromString method.

read file in an applet

Hi there I want to read out a file that lies on the server.
I get the path to the file by a parameter
<PARAM name=fileToRead value="http://someserver.de/file.txt">
when I now start the applet following error occurs
Caused by: java.lang.IllegalArgumentException: URI scheme is not "file"
Can someone give me a hint?
BufferedReader file;
String strFile = new String(getParameter("fileToRead"));
URL url = new URL(strFile);
URI uri = url.toURI();
try {
File theFile = new File(uri);
file = new BufferedReader(new FileReader(new File(uri)));
String input = "";
while ((input = file.readLine()) != null) {
words.add(input);
}
} catch (IOException ex) {
Logger.getLogger(Hedgeman.class.getName()).log(Level.SEVERE, null, ex);
}
File theFile = new File(uri);
is not the correct method. You accessing an URL, not a File.
Your code should look like this:
try
{
URL url = new URL(strFile);
InputStream in = url.openStream();
(... read file...)
in.close();
} catch(IOException err)
{
(... process error...)
}
You are trying open as a file, something which doesn't follow the file:// uri, as the error suggests.
If you want to use a URL, I suggest you just use url.openStream() which should be simpler.
You will need to sign the applet unless the file is being accessed from the same server/port that the applet came from.

Categories

Resources