...
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
Customer cc = new Customer("Selvyn", "Wright", LocalDate.of(1965, 5, 8), "Birmingham, UK"); Account acc = new Account(cc, 1); cc.setAccount( acc ); sw = Writer.getTextFileWriter("c:\\tmp\\account.json"); sw.write(FormatFactory.getFormatter(WriterMode.JSON_WRITER).format(acc)); sw.close(); sw = Writer.getTextFileWriter("c:\\tmp\\account.xml"); sw.write(FormatFactory.getFormatter(WriterMode.XML_WRITER).format(acc)); sw.close(); sw = Writer.getTextFileWriter("c:\\tmp\\customer.json"); sw.write(FormatFactory.getFormatter(WriterMode.JSON_WRITER).format(cc)); sw.close(); |
Activity 3 (~ 30 mins )
Implement code to read the data from the file back into your program. Once loaded, display it on the screen using System.out.println(). Make use of the following interface
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public interface InputChannel |
...
{
...
{ public String read(); |
...
public void close(); |
...
}
Solution
Panel | |
---|---|
bgColor | #fff
}
|
Here is the implementation of the interface
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
public class TextFileReader implements InputChannel
{
private String itsFileName;
private BufferedReader itsFileReader;
public TextFileReader()
{
}
public void openForWriting( String fname )
{
itsFileName = fname;
try
{
itsFileReader = new BufferedReader(new FileReader(fname));
} catch (IOException ex)
{
Logger.getLogger(TextFileWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String read()
{
StringBuilder sb = new StringBuilder();
String line;
try
{
while( (line = itsFileReader.readLine()) != null )
sb.append(line );
} catch (IOException ex)
{
Logger.getLogger(TextFileReader.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
close();
}
return sb.toString();
}
@Override
public void close()
{
try
{
itsFileReader.close();
} catch (IOException ex)
{
Logger.getLogger(TextFileReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
Related articles
Filter by label (Content by label) | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
...