Create a text file using PrintWriter - java

PrintWriter p;
try {
p = new PrintWriter(new FileWriter("xp.mdb"));
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
p.println("mytext");
p.close();
I'm new to Android programming and don't quite understand how writing to files work. I want to create a new file and write some text to it. The above code works on Windows but on Android I just keep getting FileNotFoundException.
How can I make it create the file if it doesn't exist?

You need to put the file in internal storage, external storage, or (on Android 4.4+) removable storage. Passing a bare filename does not work on Android.

Related

Trying to get an android app to access a CSV file to edit and write to, but it can't seem to find the file

Even though I've given the program the exact path to the csv file, it still doesn't exist according to the program. I've got no idea how to fix it.
public boolean SignUpFunc(String username, String password){
try {
File file = new File("C:\\Users\\altaf\\OneDrive\\Desktop\\Java\\login.csv");
BufferedReader reader = new BufferedReader(new FileReader(file.getPath()));
String line;
while ((line= reader.readLine())!= null){
//split by ,
String[] tokens = line.split(",");
//Read the data
if (username.equals(tokens[0])){
reader.close();
return false;
}
}
save(file,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void save(File file, String username, String password){
try{
BufferedWriter Bwriter = new BufferedWriter(new FileWriter(file.getPath(),true));
PrintWriter writer = new PrintWriter(Bwriter);
writer.println(username+","+password);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FilenotFound");
} catch (IOException e) {
e.printStackTrace();
}
}
The relevant code.
I've already enabled reading and writing from external storage from the manifest.
The location C:\users\blah\...... means absolutely nothing to the Android app, which is part of why it's not working. The other part is because that file doesn't reside on the device you are testing the app on.
Whether you are running this app on a mobile device or through an emulator (virtual device), you don't have direct access to your computer's drives. At best, you'll have to map a network drive for the app to access. At worst, you'll have to set up an API on your machine for the app to hit and have that access the file.
At this point, you might as well use a database for the password info, since it's likely you're going to need to save other information. Besides, CSV files have some serious issues, and beyond just the security issue of having usernames and passwords in plain text (even if they are encoded before they get to your saving methods).

saving h264 file in JAVA works, but in android it saves corrupted file

I am trying to save a stream of bytes in h264 format, to an h264 file.
I did it in JAVA, and the file is being saved and I can open it and see the video.
BUT, when I try the exact same code, in android, and I'm trying to save the file through the android device, the file is corrupted.
This is my code (both for android and for java):
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File file = new File(path, "/" + "filename2.mp4");
FileOutputStream output2 = null;
try {
output2 = new FileOutputStream(file, true);
output2.write(my_stream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
offcourse just the path is different in java and in the android version
Maybe because my_stream.toByteArray() is only one part of the whole video. Read the video stream in a loop and write it to the output stream chunk by chunk.
Alternatively there is this function that will do it for you:
Files.copy(videoInputStream, filePath, StandardCopyOptions.REPLACE_EXISTING);
Or if the input is a byte array:
Files.write(outputPath, bytes, StandardOpenOptions.WRITE,
StandardOpenOptions.CREATE_NEW,
StandardOpenOptions.CREATE);
Full documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20byte[],%20java.nio.file.OpenOption...)
https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html

Write to file is not working in Android

I have been trying to write to a file in Android. It is not working and it doesn't even create a file. It always executes the catch block. Here is the part of my program.
private void write(){
try {
FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\AndroidStudioProjects\\SunCalculator\\app\\src\\main\\res\\raw\\au_locations.txt");
Log.e("Data","path detected");
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
Log.e("Data","worked");
} catch (IOException e) {
e.printStackTrace();
Log.e("Data","not worked");
}
}
I also tried to create a File object and passing it to the FileWriter constructor. None of these worked. I am using Android Studio 2.3.3
You are trying to write a file in location C:\\Users.... which is the directory structure of Windows OS.
But Android is built upon Linux OS. To get the user writeable directory in android, you should use Environment.getExternalStorageDirectory() as below:
File file = new File(Environment.getExternalStorageDirectory(), filename);

Exporting to CSV/Excel in Java

I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.
EDIT: Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.
public static void writeToCSV(List<Map> objectList) {
String CSV_SEPARATOR = ",";
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("results.csv"), "UTF-8"));
for (Map objectDetails : objectList) {
StringBuffer oneLine = new StringBuffer();
Iterator it = objectDetails.values().iterator();
while (it.hasNext()) {
Object value = it.next();
if(value !=null){
oneLine.append(value.toString());
}
if (it.hasNext()) {
oneLine.append(CSV_SEPARATOR);
}
}
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.
If you're not getting errors, check the directory where your code is. Without a specific path, your file is being saved there.
EDIT: Since the file is being saved and you want it to open automatically, use
Runtime.getRuntime().exec("results.csv");
(For Windows - opens the csv file in the default application for csv files)
Runtime.getRuntime().exec("open results.csv");
(For Mac - opens the csv file in the default application for csv files)
recommend HSSFWorkbook to easily read and write excel files.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
To do that, the CSV reader need to read the memory of your program. This is a little complex thing to do. So, save the file in a temp folder instead. There is no problem to do this sort of thing.

Jar with compressed music with java?

I've tried to add music to an application I've made. First I tried with .wav files though they became so huge that the application became too large to upload anywhere.
So I changed the files to .mp3, tried JMF and JLayer though both of them won't work on runnable jars (even if they work fine when I haven't exported them).
So anyone got any tips on how to play compressed music with a runnable jar?
Here's the code for JLayer, when exported it stops working at f = new File(u.toURI()) without throwing any exceptions...
try {
URL u = cl.getResource("New Beginnings.mp3");
f = new File(u.toURI());
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream(f);
p = new Player(fis);
p.play();
} catch (Exception e) {
System.out.println(e);
}
Edit: Fixed with changing the above code to:
try {
InputStream fis = ClassLoader.getSystemClassLoader().getResourceAsStream(temp+".mp3");
p = new Player(fis);
p.play();
} catch (Exception e) {
System.out.println(e);
}
Where did you place the sound file exactly?
You should create a new package inside your project and place the resources there, then read the file by sending a complete path:
ex. create a new package called sounds, then:
InputStream fis = ClassLoader.getSystemClassLoader().getResourceAsStream("/sounds/"+temp+".mp3");
p = new Player(fis);
p.play();
To be honest, I didn't try it with sounds, but this problem happened to me when I used images. I placed them in a package, and everything worked fine..

Categories

Resources