Java how to print filename? - java

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
try {
FileReader fin = new FileReader("c:\\windows\\system.ini");
Scanner scn = new Scanner(fin);
while (scn.hasNext()) {
String tmp = scn.nextLine();
System.out.println(tmp);
}
fin.close();
scn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how can i print c:\windows\system.ini (path? file?name).
Is there any way to print the path?

Check this out:
try {
File file = new File("c:\\windows\\system.ini");
FileReader fileReader = new FileReader(file);
System.out.println(file.getName());
System.out.println(file.getPath());
Scanner scn = new Scanner(fileReader);
while (scn.hasNext()) {
String tmp = scn.nextLine();
System.out.println(tmp);
}
fileReader.close();
scn.close();
}catch (Exception e) {
}
you can use File then pass it to FileReader.

Related

Displaying the contents of a textfile by typing the filename in a java program?

Write a program that reads in a file and displays its contents. Get the input filename from the command line. For example, if your program is in the file Display.class, you would enter on the command line:
java Display t1.txt
to display the content file t1.txt.
How can this be done?
you can use FileReader or BufferedReader to read the contents of file. below code may be helpful to you
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Display {
public static void main(String[] args) {
if(args.length > 0) {
String fileName = args[0];
try {
File file = new File(fileName);
if(file.exists() && file.isFile() ) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
System.out.println("FileContents are...");
while((line = br.readLine()) != null) {
System.out.println(line);
}
}else{
System.out.println("File Not Found");
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Java: Multi line output via Socket

i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Read and edit the file from Java

I'm trying to introduce a line break at every 100th character of the line from the existing file.But it doesn't write anything to it. below is the code written in java to read the existing file and write to it with a temporary file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
First off, line.replaceAll does not replace your line variable with the result. Because Strings are immutable, this method returns the new string, so your line should be line = line.replaceAll(....
Second, you're never writing the new String back into the file. Using replaceAll doesn't change the file itself in any way. Instead, try using your bw object to write the new String to the same line.
From what you've published here, you never try to write line back to bw. Try this:
package hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
new Test().replace();
}
public void replace() {
String oldFileName = "d:\\1.txt";
String tmpFileName = "d:\\2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("(.{100})", "$1\n");
bw.write(line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
You never try to write line back to bw;
String#replaceAll will return the copy of the source not the original String;

Reading text file into String array, then converting to ArrayList

How can I read a file into a array of String[] and then convert it into ArrayList?
I can't use an ArrayList right away because my type of list is not applicable for the arguments (String).
So my prof told me to put it into an array of String, then convert it.
I am stumped and cannot figure it out for the life of me as I am still very new to java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tsenyurt on 06/04/15.
*/
public class ReadFile
{
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
there is a code that reads a file and create a ArrayList from it
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Well there are many ways to do that,
you can use this code if you want have a List of each word exist in your file
public static void main(String[] args) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(
"Your file path"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
String[] words = sb.toString().split("\\s");
list = Arrays.asList(words);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String string : list) {
System.out.println(string);
}
}

Using exceptions in Java with user I/O

I am trying to do the following: I am making a program in Java which let me create and read text files. So far I have been able to do this, but the hard(?) part is this: I have to be able to get an error when anything else but A, B or C is inside the text file.
So far I got:
package textfile;
import java.io.*;
import static java.lang.System.*;
class OutWrite {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("FAS.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("A");
pw.println("B");
pw.println("C");
pw.close();
} catch (IOException e){
out.println("ERROR!");
}
}
}
And
package textfile;
import java.io.*;
import static java.lang.System.*;
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
out.println(str);
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
}
}
Can anyone steer me in the right direction, please?
Just throw Exception when a new Character is found other than A,B,C .
use,
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
out.println(str);
else
throw new Exception(); //throw exception
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
catch (Exception e) {//catch it here and print the req message
System.out.println("New Character Found");
}
}
}

Categories

Resources