How to read file in ideone in java - java

I want to open, read, and edit file from my desktop. I am using Ideone online compiler. How do I read the file? I tried the following code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class demo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
File file = new File("C:/Users/psanghavi/Desktop/admin_confirmation_original.txt");
if (!file.exists())
{
System.out.println("does not exist.");
return;
}
if (!(file.isFile() && file.canRead()))
{
System.out.println(file.getName() + " cannot be read from.");
return;
}
try
{
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0)
{
current = (char) fis.read();
System.out.print(current);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
My desktop has file named: admin_confirmation_original.txt

Currently, No. About the limit, Idebone FAQ say about this:
Can I write or read files in my program? - No
Can I access the network from my program? - No
You can learn more about many Ideone restricted rule at FAQ.

Ideoone doesn't support reading local files.
This is not an answer to your question, but wrt to the comments
if you want to read files hosted, you could access them using URL class.
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Demo {
public static void main(String[] args) throws IOException {
try {
final URL url = new URL("http://www.google.co.in/robots.txt");
//URL url = new URL("http://74.125.236.52/robots.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while (in.readLine() != null) {
str = in.readLine();
System.out.println(str);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have not tried it on file hosting sites.There are a lot of free file hostings available just google it.

Related

How to print contents of a text to console as objects

Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * BufferedReader and Scanner can be used to read
line by line from any File or
 * console in Java.
 * This Java program
demonstrate line by line reading using BufferedReader in Java
 *
 * #author Javin Paul
 */
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

see the content of a .bson file using java

I have a very large .bson file.
Now I have two question:
How can I see the content of that file? (I know it can do with "bsondump", but this command is slow, specialy for large database) (In fact I want to see the structure of that file)
How can I see the content of that file using java?
You can easily read/parse a bson file in Java using a BSONDecoder instance such as BasicBSONDecoder or DefaultBSONDecoder. These classes are included in mongo-java-driver.
Here's a simple example of a Java implementation of bsondump.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.bson.BSONDecoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
public class BsonDump {
public void bsonDump(String filename) throws FileNotFoundException {
File file = new File(filename);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BSONDecoder decoder = new BasicBSONDecoder();
int count = 0;
try {
while (inputStream.available() > 0) {
BSONObject obj = decoder.readObject(inputStream);
if(obj == null){
break;
}
System.out.println(obj);
count++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
}
System.err.println(String.format("%s objects read", count));
}
public static void main(String args[]) throws Exception {
if (args.length < 1) {
//TODO usage
throw new IllegalArgumentException("Expected <bson filename> argument");
}
String filename = args[0];
BsonDump bsonDump = new BsonDump();
bsonDump.bsonDump(filename);
}
}

Run an interactive Dos program from java

I would like to run a Dos program from a web server. The Dos program has to be run interactively as the user interface is via a series of questions and answers. The answer to one question will determine the next question. I will have to use ajax on the web server, but I think I can do that.
I found one java program on Stackoverflow which seems to do something similar to what I want. However when I compile the program I get an error ie.
javac PipeRedirection.java
PipeRedirection.java:43: package InputProcess does not exist
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
The stack overflow question url was
How can I write large output to Process getOutputStream?
The Java file was
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Does anyone know why I get the compile error? Can I substitute some other code for InputProcess?
Thanks for any help
Peter
I think it's pretty obvious that you're missing parts to this code. A package named InputProcess which has a class called Gobbler was not included in the OP's post. Probably because it was not relevant to their question.
The error message essentially says that it can not find this package/code that it is looking for.
What this class does exactly, only the OP can tell you. At its most basic, though, it appears to read from an InputStream and convert it to a List<String>. I would read up on Java IO and try to replicate similar functionality.
Edit:
Looks like the Gobbler class is indeed included in the example above. Remove the InputProcess package name from your code (or put the Gobbler class in an InputProcess package) and you should be good to go.

how to read directories in java

simple: how do i read the contents of a directory in Java, and save that data in an array or variable of some sort? secondly, how do i open an external file in Java?
You can use java IO API. Specifically java.io.File, java.io.BufferedReader, java.io.BufferedWriter etc.
Assuming by opening you mean opening file for reading. Also for good understanding of Java I/O functionalities check out this link: http://download.oracle.com/javase/tutorial/essential/io/
Check the below code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileIO
{
public static void main(String[] args)
{
File file = new File("c:/temp/");
// Reading directory contents
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
// Reading conetent
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
String line = null;
while(true)
{
line = reader.readLine();
if(line == null)
break;
System.out.println(line);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
You can use a class java.io.File to do that. A File is an abstract representation of file and directory pathnames. You can retrieve the list of files/directories within it using the File.list() method.
There's also the Commons IO package which has a variety of methods for manipulating files and directories.
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class CommonsIO
{
public static void main( String[] args )
{
// Read the contents of a file into a String
try {
String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) );
} catch (IOException e) {
e.printStackTrace();
}
// Get a Collection of files in a directory without looking in subdirectories
Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null );
for ( File f : files ) {
System.out.println( f.getName() );
}
}
}
public class StackOverflow {
public static void main(String[] sr) throws IOException{
//Read a folder and files in it
File f = new File("D:/workspace");
if(!f.exists())
System.out.println("No File/Dir");
if(f.isDirectory()){// a directory!
for(File file :f.listFiles()){
System.out.println(file.getName());
}
}
//Read a file an save content to a StringBuiilder
File f1 = new File("D:/workspace/so.txt");
BufferedReader br = new BufferedReader(new FileReader(f1));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
sb.append(line+"\n");
System.out.println(sb);
}
}

Categories

Resources