Save to txt (java) [duplicate] - java

This question already has answers here:
How do you Programmatically Download a Webpage in Java
(11 answers)
Closed 6 years ago.
How can I make the below code, save the webpage it self to txt file, I don't need the code of the webpage I need the webpage itself to be saved as text, like when we press CTRL + S and choose save as txt.
As well, how to make the browse hidden.
Thank you in advance :)
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
public class Main {
public static void main(String[] args) throws Exception {
Desktop d = Desktop.getDesktop();
String url = "http://w3-01.ibm.com/pc/entitle/pg2/Service.wss/mts/Lookup?type=8205&serial=06202ET";
d.browse(new URI(url));
}
}

Here is a working example in Java 8:
import java.io.*;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.google.com/");
String file = System.getProperty("java.io.tmpdir") + "google.txt";
System.out.println("Saving file to " + file);
try (InputStream in = url.openStream();
OutputStream os = new FileOutputStream(file)) {
int b;
while ((b = in.read()) != -1) {
os.write(b);
}
}
}
}

Related

Cannot find symbol even with class imported

I have a bit of a weird situation.
The problem is with import java.nio.*; and import java.nio.file.Paths;.
First of all, import java.nio.*; should import the second class anyway, but I'm experiencing something weird. It might be a known mistake I'm making but I'm new to Java.
If I import both, or if I import only java.nio.*, I get error: cannot find symbol for Files.write(...). However, if I import only java.nio.file.Paths, I get the same error but for Paths.get(...).
Any idea as to why this is happening? I'm open to exploring other options than these two classes, all I want to do is append a text file.
public static void addAction(String cmd) {
String text = "Text to save to file";
Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}
is the bit where the problem is, but in case it's a problem with something else that I wrote I've attached the whole file below:
import java.io.File; // Find Files
import java.awt.FileDialog; // File Picker
import javax.swing.JFrame; // JFrame
import java.nio.*;
// import java.nio.file.Paths;
class Files {
public static void getApps(final File folder) {
for (final File file : folder.listFiles()) {
String fileName = file.getName();
// System.out.println(fileName);
// System.out.println(file.getPath());
final File subfolder = new File(file.getPath()+"/Contents/Resources");
if (subfolder.exists()) {
String icon = pickFile(subfolder.getPath());
if (icon == null) return;
System.out.println("App Name: " + fileName);
System.out.println("Icon Name: " + icon);
} else {
System.out.println("Directory not found...");
}
}
}
public static String pickFile(String path) {
FileDialog dialog = new FileDialog(new JFrame(), "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setFilenameFilter((File dir, String name) -> name.endsWith(".icns"));
dialog.setDirectory(path);
dialog.setVisible(true);
String fileChosen = dialog.getFile();
return fileChosen;
}
public static void addAction(String cmd) {
String text = "Text to save to file";
Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}
public static void main (String[] args) {
String action = "{\n\"BTTTouchBarButtonName\":\"Messages\",\n\"BTTTriggerType\":629,\n\"BTTTriggerClass\":\"BTTTriggerTypeTouchBar\",\n\"BTTPredefinedActionType\":49,\n\"BTTPredefinedActionName\":\"Launch Application \\/ Open File \\/ Start Apple Script …\",\n\"BTTLaunchPath\":\"file:\\/\\/\\/Applications\\/Messages.app\",\n\"BTTEnabled2\":1,\n\"BTTUUID\":\"F3089B96-FDEF-4D54-9DA8-9CCD3C7AF8A9\",\n\"BTTEnabled\":1,\n\"BTTRequiredModifierKeys\":1048576,\n\"BTTOrder\":1,\n \"BTTIconData\":\"icondata\",\n\"BTTTriggerConfig\":{\n\"BTTTouchBarItemIconHeight\":22,\n\"BTTTouchBarItemIconWidth\":22,\n\"BTTTouchBarItemPadding\":0,\n\"BTTTouchBarFreeSpaceAfterButton\":\"5.000000\",\n\"BTTTouchBarButtonColor\":\"75.323769, 75.323769, 75.323769, 255.000000\",\n\"BTTTouchBarAlwaysShowButton\":\"1\",\n\"BTTTouchBarAlternateBackgroundColor\":\"0.000000, 0.000000, 0.000000, 0.000000\"\n}\n}";
File f = new File("/Users/Andrew/Desktop/testfile.txt");
try {f.createNewFile();}catch(Exception e){}
addAction("open 'btt://add_new_trigger/?json="+action+"'");
}
}
Edit: I am using JDK Version 8-171 for Mac
Java compiler is getting confused because Files is the name of your class so it is looking for a write method in your class. Try leaving only this import :
import java.nio.file.Paths;
And then call the complete class name for java.nio.file.Files:
java.nio.file.Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
But then you should handle your IOException also. Add your import and try/catch. Here is your class with no compilation errors:
import java.io.File; // Find Files
import java.io.IOException;
import java.awt.FileDialog; // File Picker
import javax.swing.JFrame; // JFrame
import java.nio.file.Paths;
class Files {
public static void getApps(final File folder) {
for (final File file : folder.listFiles()) {
String fileName = file.getName();
// System.out.println(fileName);
// System.out.println(file.getPath());
final File subfolder = new File(file.getPath()+"/Contents/Resources");
if (subfolder.exists()) {
String icon = pickFile(subfolder.getPath());
if (icon == null) return;
System.out.println("App Name: " + fileName);
System.out.println("Icon Name: " + icon);
} else {
System.out.println("Directory not found...");
}
}
}
public static String pickFile(String path) {
FileDialog dialog = new FileDialog(new JFrame(), "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setFilenameFilter((File dir, String name) -> name.endsWith(".icns"));
dialog.setDirectory(path);
dialog.setVisible(true);
String fileChosen = dialog.getFile();
return fileChosen;
}
public static void addAction(String cmd) {
String text = "Text to save to file";
try{
java.nio.file.Files.write( Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}catch(IOException e){
System.err.print("Handle your error!");
}
}
public static void main (String[] args) {
String action = "{\n\"BTTTouchBarButtonName\":\"Messages\",\n\"BTTTriggerType\":629,\n\"BTTTriggerClass\":\"BTTTriggerTypeTouchBar\",\n\"BTTPredefinedActionType\":49,\n\"BTTPredefinedActionName\":\"Launch Application \\/ Open File \\/ Start Apple Script …\",\n\"BTTLaunchPath\":\"file:\\/\\/\\/Applications\\/Messages.app\",\n\"BTTEnabled2\":1,\n\"BTTUUID\":\"F3089B96-FDEF-4D54-9DA8-9CCD3C7AF8A9\",\n\"BTTEnabled\":1,\n\"BTTRequiredModifierKeys\":1048576,\n\"BTTOrder\":1,\n \"BTTIconData\":\"icondata\",\n\"BTTTriggerConfig\":{\n\"BTTTouchBarItemIconHeight\":22,\n\"BTTTouchBarItemIconWidth\":22,\n\"BTTTouchBarItemPadding\":0,\n\"BTTTouchBarFreeSpaceAfterButton\":\"5.000000\",\n\"BTTTouchBarButtonColor\":\"75.323769, 75.323769, 75.323769, 255.000000\",\n\"BTTTouchBarAlwaysShowButton\":\"1\",\n\"BTTTouchBarAlternateBackgroundColor\":\"0.000000, 0.000000, 0.000000, 0.000000\"\n}\n}";
File f = new File("/Users/Andrew/Desktop/testfile.txt");
try {f.createNewFile();}catch(Exception e){}
addAction("open 'btt://add_new_trigger/?json="+action+"'");
}
}
In my case it was a JAVA project and the class was written in Kotlin (copy-paste), so I added Kotlin dependencies and the problem is solved.

decreasing in size when reversing and storing text from a file to another using Java

I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.

List attached devices on ubuntu in java

I'm a little stumped, currently I am trying to list all of the attached devices on my system in linux through a small java app (similar to gparted) I'm working on, my end goal is to get the path to the device so I can format it in my application and perform other actions such as labels, partitioning, etc.
I currently have the following returning the "system root" which on windows will get the appropriate drive (Ex: "C:/ D:/ ...") but on Linux it returns "/" since that is its technical root. I was hoping to get the path to the device (Ex: "/dev/sda /dev/sdb ...") in an array.
What I'm using now
import java.io.File;
class ListAttachedDevices{
public static void main(String[] args) {
File[] paths;
paths = File.listRoots();
for(File path:paths) {
System.out.println(path);
}
}
}
Any help or guidance would be much appreciated, I'm relatively new to SO and I hope this is enough information to cover everything.
Thank you in advance for any help/criticism!
EDIT:
Using part of Phillip's suggestion I have updated my code to the following, the only problem I am having now is detecting if the selected file is related to the linux install (not safe to perform actions on) or an attached drive (safe to perform actions on)
import java.io.File;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import javax.swing.filechooser.FileSystemView;
class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> dev = new ArrayList<File>();
for (FileStore store : FileSystems.getDefault().getFileStores()) {
String text = store.toString();
String match = "(";
int position = text.indexOf(match);
if(text.substring(position, position + 5).equals("(/dev")){
if(text.substring(position, position + 7).equals("(/dev/s")){
String drivePath = text.substring( position + 1, text.length() - 1);
File drive = new File(drivePath);
dev.add(drive);
FileSystemView fsv = FileSystemView.getFileSystemView();
System.out.println("is (" + drive.getAbsolutePath() + ") root: " + fsv.isFileSystemRoot(drive));
}
}
}
}
}
EDIT 2:
Disregard previous edit, I did not realize this did not detect drives that are not already formatted
Following Elliott Frisch's suggestion to use /proc/partitions I've come up with the following answer. (Be warned this also lists bootable/system drives)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> drives = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader("/proc/partitions"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
String text = line;
String drivePath;
if(text.contains("sd")){
int position = text.indexOf("sd");
drivePath = "/dev/" + text.substring(position);
File drive = new File(drivePath);
drives.add(drive);
System.out.println(drive.getAbsolutePath());
}
line = br.readLine();
}
} catch(IOException e){
Logger.getLogger(ListAttachedDevices.class.getName()).log(Level.SEVERE, null, e);
}
finally {
br.close();
}
}
}

Determine image extension [duplicate]

This question already has answers here:
How to extract file extension from byte array
(3 answers)
Closed 7 years ago.
I am developing a web app, which has the functionality of displaying images obtained from a server. I learned that I can do it by returning byte array in response.
It seems that I am able to do it through:
#RequestMapping(value = "url/img", method = RequestMethod.POST)
#ResponseBody
public MyDto proceedDocumentFromUrl(#RequestParam final String url) throws IOException {
return somethingDoer.do(toByteArray(new URL(url).openStream());
}
somethingDoer.do returns Dto object which contains byte[] In field named image. For test purposes I would like to determine the image extension (it is always .jpg).
How can I do that? I was looking in Wiki and W3 documents for some clue(I suppose it is about first few bytes) but was unable to find a solution.
Please check this getFormatName(file) method and check Class ImageReader
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("image.gif");
System.out.println(getFormatName(file));
InputStream is = new FileInputStream(file);
is.close();
System.out.println(getFormatName(is));
}
private static String getFormatName(Object o) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(o);
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader) iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
}
return null;
}
}
Please check https://github.com/arimus/jmimemagic to get extension from byte[]
byte[] data = someData
MagicMatch match = Magic.getMagicMatch(data);
System.out.println( match.getMimeType());

Return of getProperty() can't be used in if statement whereas same value as String variable works [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my first post here and I hope to find some help as I#m not only new to this site but also to Java.
For a game I am using Properties (with a corresponding file) to save and load settings.
I also have written a language system where I now get problems (Explained under the code)
Language class: Lang.java :
package de.cozmic.phaseone.reference;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import de.cozmic.phaseone.PhaseOne;
import de.cozmic.phaseone.console.Console;
public class Lang {
private static String path = null;
public static final String en = "en";
public static final String de = "de";
public static final String it = "it";
public static final String fr = "fr";
public static Properties lang = new Properties();
public Lang() {
String language = PhaseOne.settings.getProperty("Language");
//language = de; //FOR TESTING
Console.addLine("Starting Language : " + language);
if (language == en) path = "en.l";
if (language == de) path = "de.l";
if (language == it) path = "it.l";
if (language == fr) path = "fr.l";
Console.addLine("First Tried Language Path : " + path);
if (path == null) path = "en.l";
Console.addLine("Final Language Path : " + path);
try {
InputStream in = Lang.class.getResourceAsStream(path);
lang.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
}
public static void use(String language) {
try {
FileInputStream in = new FileInputStream(language);
lang.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
reload();
}
private static void reload() {
//TODO
}
}
Main class: PhaseOne.java
package de.cozmic.phaseone;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import de.cozmic.phaseone.console.Console;
import de.cozmic.phaseone.console.Log;
import de.cozmic.phaseone.display.FLauncher;
import de.cozmic.phaseone.input.InputHandler;
import de.cozmic.phaseone.reference.Lang;
import de.cozmic.phaseone.reference.Reference;
public class PhaseOne {
public static Properties settings = new Properties();
public PhaseOne() {
new Log();
new InputHandler();
loadSettings();
new Lang();
new FLauncher();
}
private void loadSettings() {
File f = new File("settings.p");
if (!f.exists())
try {
f.createNewFile();
FileOutputStream out = new FileOutputStream(f.getAbsolutePath());
settings.setProperty("Language", Lang.en);
settings.setProperty("GameWidth", String.valueOf(Reference.WIDTH));
settings.setProperty("GameHeight", String.valueOf(Reference.HEIGHT));
settings.store(out, null);
out.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
try {
Console.addLine("Loading settings");
FileInputStream in = new FileInputStream(f.getAbsolutePath());
settings.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
Console.addLine("Error: Loading settings failed!");
e.printStackTrace();
}
Console.addLine("Loaded settings:");
Enumeration<?> enu = settings.propertyNames();
while (enu.hasMoreElements()) {
String set = (String) enu.nextElement();
Console.addLine(set + " : " + settings.getProperty(set));
}
}
public static void changeSettings(String setting, String value) {
settings.setProperty(setting, value);
}
public static void main(String[] args) {
new PhaseOne();
}
}
Basically everything is working correctly and the properties are used correctly to display the text.
The problem is that it works as long as I directly use a String variable containing "de", but nut if I let the program read the same (!) value "de" from the properties. In the Lang() Constructer it gets null for the path whereas when I used "de" for the language variable it worked correctly.
This is the settings.p:
#Thu Aug 14 23:33:31 CEST 2014
GameWidth=800
GameHeight=600
Language=de
And this is (the relevant part of) the Log file:
Loading settings
Loaded settings:
Language : de
GameWidth : 800
GameHeight : 600
Starting Language : de
First Tried Language Path : null
Final Language Path : en.l
I hope anyone can tell me what is wrong or give a suggestion what to try to get it working.
I looked over it several times and really don't see why it should be behaving like this.
Also in the log you can clearly see that the variable language actually is right, just the if statement doesn't recognize it for whatever reason.
Like I said when I directly give it the String value everything works as intended.
Thanks in advance for everyone who is reading this!
Strings are objects, and as such should not be compared for contents using ==. == is only for reference equality. Rewrite your block as:
if (en.equals(language)){
or better yet, with a switch statement:
switch(language){
case "en":
path = "en.l";
break;
case "de":
path = "de.l";
break;
// More cases...
default:
// handle invalid language error case
}

Categories